如何创建这样的方法:如何检查ruby中的类属性?
def process_by_type *things
things.each {|thing|
case thing.type
when String
when Array
when Hash
end
end
}
end
我知道我可以使用kind_of(阵列)等,但我认为这将是更清洁,而且我不能”为它找到一个方法的类:对象文档页面。
如何创建这样的方法:如何检查ruby中的类属性?
def process_by_type *things
things.each {|thing|
case thing.type
when String
when Array
when Hash
end
end
}
end
我知道我可以使用kind_of(阵列)等,但我认为这将是更清洁,而且我不能”为它找到一个方法的类:对象文档页面。
使用情况说明的形式就像你在做什么:
case obj
when expr1
# do something
when expr2
# do something else
end
相当于执行了一堆如果expr === OBJ(三重等于比较)。当expr是类类型时,如果obj是表达式或表达式的一个子类型,则===比较返回true。
因此,下面应该做你所期望的:
def process_by_type *things
things.each {|thing|
case thing
when String
puts "#{thing} is a string"
when Array
puts "#{thing} is an array"
when Hash
puts "#{thing} is a hash"
else
puts "#{thing} is something else"
end
}
end
啊,非常感谢!我曾见过这样的事情,并认为它有一些神秘感,但现在我明白了! – 2011-06-11 17:05:03
尝试.class:
>> a = "12"
=> "12"
>> a.class
=> String
>> b = 42
=> 42
>> b.class
=> Fixnum
如果你可以使用kind_of或is_a,这绝对是更好地使用它们。 – Spyros 2011-06-11 16:57:46
为什么?我没有看到任何危险。 – 2011-06-11 17:00:40
只是因为没有重新发明轮子的意义,而且这些方法已被广泛使用和测试。 – Spyros 2011-06-11 17:05:38