开发者

ruby way of checking if an object is in an array

I come from the Java world so I was sh开发者_如何学JAVAocked to discover that arrays (http://ruby-doc.org/core/classes/Array.html) does not hava a method contains(object) returning bool.

What is the good way - the Ruby way - of doing that ?


array.include?(obj) → true or false

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

a = [ "a", "b", "c" ]
a.include?("b")   #=> true
a.include?("z")   #=> false

This, from the Array class documentation:


[1,2,3].include? 2
=> true


ruby-1.9.2-p0 > [1,2,3].include? 3
 => true 

ruby-1.9.2-p0 > [1,2,3].include? 33
 => false 


You can do this:

Array.index("ITEM")

if the result is != de nil the element exists.

Regards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜