在Ruby中键入数组索引值的检查

时间:2013-05-20 07:39:19

标签: ruby

在Javascript中,如果我想对数组索引进行类型检查,我可以这样做:

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");

    }

}

在Ruby中,我不明白如何做到这一点。我正在尝试对整数进行检查。 据我所知,在Ruby世界中,使用每种方法都被认为是很好的礼仪,因此基本的循环是这样的:

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

我很困惑的部分是语法是外来的,我不清楚逻辑在哪里。我还没有进行实际的类型检查,但是根据我的阅读,它将与 Integer 类型进行比较,因此:

if array[i] == Integer

谢谢。

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

这将是最直接的,而不是嘈杂。

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

我在这里使用Numeric而不是Integer,因为您的日志暗示您正在尝试确保它是一个数字,而不一定是整数。所以这将允许Float,Integer,BigDecimal等。

根据该答案,一般情况下,您可以将其作为一个组报告给日志。

如果您想记录单个项目,那么使用eacheach_with_index是可行的方法。

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

答案 2 :(得分:0)

在测试object == Integer时,您说Is my object, the Integer class?但您想知道对象是否是此类的实例,而不是类本身。

在Ruby中,要测试实例的类,你可以做

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
顺便提一下,2.class => Fixnum 您可以使用

查看对象的类
array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x.class }