William
William

Reputation: 4588

Type checking of array index value in Ruby

In Javascript if I want to do type checking of an array index I can do something like this:

var array = [1,2,3,4,"the monster from the green lagoon"]

for (i=0;  i < array.length;  i++) {

    if (typeof(array[i]) === 'number')      {
    console.log("yes these are all numbers");

    }

    else        {
    console.log("Index number " + i + " is " +  array[i] +": No this is not a number");

    }

}

In Ruby I don't understand how to do this. I'm trying to type check against Integers. I understand that in the Ruby world it's considered good etiquette to use the each method thus basic looping is something like this:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

The part I'm confused about is the syntax is foreign and I'm unclear where the logic goes. I haven't gotten to the actual type checking yet but from what I read it would compare against the Integer type thus:

if array[i] == Integer

Thank you.

Upvotes: 0

Views: 4063

Answers (3)

vgoff
vgoff

Reputation: 11323

This would be most straight forward, and not noisy.

array.all? {|x| x.is_a? Numeric}

I use Numeric here rather than Integer as your log implies that you are trying to ensure it is a number, not necessarily an Integer. So this will allow Float, Integer, BigDecimal, etc.

Based on that answer, in general, you could then report it to a log, as a group.

If you want to log individual items, then using each or perhaps each_with_index is the way to go.

 array.each_with_index {|x, i| $LOG.puts "element at #{i} that is #{x.inspect} is not a number" unless x.kind_of? Numeric }

Upvotes: 1

halfelf
halfelf

Reputation: 10107

a = [1,2,3,4,5]
a.all? { |x| x.is_a? Integer } 

Upvotes: 8

oldergod
oldergod

Reputation: 15010

When testing object == Integer, you are saying Is my object, the Integer class? but you want to know if object is an instance of this class, not the class itself.

In Ruby, to test an instance's class you can do

Integer === object
object.is_a?(Integer)
object.instance_of?(Integer)
object.kind_of?(Integer) # returns true when object is a subclass of Integer too !
object.class == Integer

※ by the way, 2.class => Fixnum.
You can see your objects' class with

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x.class }

Upvotes: 0

Related Questions