In Ruby, how can I find a value in an array?
Use:
myarray.index "valuetoFind"
That will return you the index of the element you want or nil if your array doesn't contain the value.
If you want find one value from array, use Array#find:
arr = [1,2,6,4,9]
arr.find {|e| e%3 == 0} #=> 6
See also:
arr.select {|e| e%3 == 0} #=> [ 6, 9 ]
e.include? 6 #=> true
To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in?
works for any object that responds to #include?
:
arr = [1, 6]
6.in? arr #=> true
This answer is for everyone that realizes the accepted answer does not address the question as it currently written.
The question asks how to find a value in an array. The accepted answer shows how to check whether a value exists in an array.
There is already an example using index
, so I am providing an example using the select
method.
1.9.3-p327 :012 > x = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
1.9.3-p327 :013 > x.select {|y| y == 1}
=> [1]
You can go for array methods.
To see all array methods use methods
function with array.
For Example,
a = ["name", "surname"]
a.methods
By the way you can use different method for checking value in array
You can use a.include?("name")
.