I have an array of hashes, @fathers.
a_father = { \"father\" => \"Bob\", \"age\" => 40 }
@fathers << a_father
a_father = { \"father\" => \"Da
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."
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
this will return first match
@fathers.detect {|f| f["age"] > 35 }
(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 }