Ruby: finding items in a hash by value
I am currently working with a ruby ββhash that looks like this:
{"employee"=>[{"name"=>"john", "level"=>"1", "position"=>"S1"}, {"name"=>"bill", "level"=>"2", "position"=>"S2"}]}
These are two examples of employees, and I need to be able to pull out employees by values. For example, I would like to get all employees who have level == 2, or all employees who position == S1.
How can I do this in Ruby?
Use Hash#select
or Array#select
.
level_2_employees = infoHash["employee"].select {|k| k["level"] == "2"}
This will return an array of hashes of employee information according to your criteria. Remember to put quotation marks around the value for the level.
ehash = {"employee"=>[{"name"=>"john", "level"=>"1", "position"=>"S1"}, {"name"=>"bill", "level"=>"2", "position"=>"S2"}]} ehash['employee'].find_all { |e| e['level'] == 2} ehash['employee'].find_all { |e| e['position'] == 'S2'}