How do I search within an array of hashes by hash values in ruby?

RubySearchHashArrays

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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."

Solution 2 - Ruby

this will return first match

@fathers.detect {|f| f["age"] > 35 }

Solution 3 - Ruby

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

Solution 4 - Ruby

(Adding to previous answers (hope that helps someone):)

Age is simpler but in case of string and with ignoring case:

  • Just to verify the presence:

@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.

  • To find first instance/index:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • To select all such indices:

@fathers.select { |father| father[:name].casecmp("john") == 0 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoctororangeView Question on Stackoverflow
Solution 1 - RubyJordan RunningView Answer on Stackoverflow
Solution 2 - RubyNaveedView Answer on Stackoverflow
Solution 3 - RubyHitesh RanautView Answer on Stackoverflow
Solution 4 - RubyARKView Answer on Stackoverflow