[{"name"=>"john", "level"=>"1...">

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?

+8
ruby
source share
2 answers

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.

+23
source share
 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'} 
+5
source share

Source: https://habr.com/ru/post/649914/


All Articles