I have an array of hashes, @fathers.
a_father = { "father" => "Bob", "age" => 40 }
@fathers << a_father
a_father = { "father" => "David", "age" => 32 }
@fathers << a_father
a_father = { "father" => "Batman", "age" => 50 }
@fathers << a_father
How can I search this array and return an array of hashes for which a block returns true?
For example:
@fathers.some_method("age" > 35) #=> array containing the hashes of bob and batman
Thanks.
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