[英]How do I inspect the class type of attributes in ruby?
如何创建如下方法:
def process_by_type *things
things.each {|thing|
case thing.type
when String
when Array
when Hash
end
end
}
end
我知道我可以使用 kind_of?(Array) 等。但我认为这会更干净,我无法在 Class:Object 文档页面上找到它的方法。
尝试.class :
>> a = "12"
=> "12"
>> a.class
=> String
>> b = 42
=> 42
>> b.class
=> Fixnum
使用 case 语句的形式,就像你正在做的那样:
case obj
when expr1
# do something
when expr2
# do something else
end
相当于执行了一堆 if expr === obj(三等比较)。 当 expr 是 class 类型时,如果 obj 是expr的类型或expr的子类,则 === 比较返回 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.