To find the index of an element in the array by specifying its value, you can use the index method. If the specified value is within the array, the method will return its index, which you can use to fetch the item.
Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.
A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
this will return first match
@fathers.detect {|f| f["age"] > 35 }
if your array looks like
array = [
{:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
{:name => "John" , :age => 26 , :place => "xtz"} ,
{:name => "Anil" , :age => 26 , :place => "xsz"}
]
And you Want To know if some value is already present in your array. Use Find Method
array.find {|x| x[:name] == "Hitesh"}
This will return object if Hitesh is present in name otherwise return nil
(Adding to previous answers (hope that helps someone):)
Age is simpler but in case of string and with ignoring case:
@fathers.any? { |father| father[:name].casecmp("john") == 0 }
should work for any case in start or anywhere in the string i.e. for "John"
, "john"
or "JoHn"
and so on.
@fathers.find { |father| father[:name].casecmp("john") == 0 }
@fathers.select { |father| father[:name].casecmp("john") == 0 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With