How do I create a method like:
如何创建这样的方法:
def process_by_type *things
things.each {|thing|
case thing.type
when String
when Array
when Hash
end
end
}
end
I know I can use kind_of?(Array), etc. But I think this would be cleaner, and I cant' find a method for it on the Class:Object documentation page.
我知道我可以使用kind_of?(数组),等等。但是我认为这样会更简洁,而且我在Class:Object documentation页面上找不到它的方法。
2 个解决方案
#1
3
Using the form of case statement like what you're doing:
使用案例陈述的形式,比如你正在做的事情:
case obj
when expr1
# do something
when expr2
# do something else
end
is equivalent to performing a bunch of if expr === obj (triple-equals comparison). When expr is a class type, then the === comparison returns true if obj is a type of expr or a subclasses of expr.
等于执行一系列if expr === = obj (triple-equals comparison)。当expr是类类型时,如果obj是expr的类型或expr的子类,则===比较返回true。
So, the following should do what you expect:
因此,以下几点应该符合您的期望:
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
#2
3
Try .class:
试试. class:
>> a = "12"
=> "12"
>> a.class
=> String
>> b = 42
=> 42
>> b.class
=> Fixnum
#1
3
Using the form of case statement like what you're doing:
使用案例陈述的形式,比如你正在做的事情:
case obj
when expr1
# do something
when expr2
# do something else
end
is equivalent to performing a bunch of if expr === obj (triple-equals comparison). When expr is a class type, then the === comparison returns true if obj is a type of expr or a subclasses of expr.
等于执行一系列if expr === = obj (triple-equals comparison)。当expr是类类型时,如果obj是expr的类型或expr的子类,则===比较返回true。
So, the following should do what you expect:
因此,以下几点应该符合您的期望:
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
#2
3
Try .class:
试试. class:
>> a = "12"
=> "12"
>> a.class
=> String
>> b = 42
=> 42
>> b.class
=> Fixnum