Ruby way to check if an object is in an array

I came from the Java world, so I was shocked to find that arrays ( http://ruby-doc.org/core/classes/Array.html ) do not have a method contains(object)that returns bool.

What is a good way - ruby ​​way - to do this?

+3
source share
4 answers

array.include? (obj) → true or false

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

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

This is from the Array class documentation :

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

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

:

Array.index("ITEM")

!= de nil, .

.

0

Source: https://habr.com/ru/post/1773021/


All Articles