Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: find items in hash by values

Tags:

ruby

I'm currently working with a ruby hash that looks like the following:

{"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 employees out by values. For example I'd like to get all employees who's level == 2, or all employees who's position == S1.

How would I do this in Ruby?

like image 222
Jeremy B. Avatar asked Dec 07 '10 18:12

Jeremy B.


People also ask

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How can you get all the values of a hash in an array Ruby?

We can use the values method to return all the values of a hash in Ruby.

How do you iterate through a hash?

Use #each to iterate over a hash.


1 Answers

Use Hash#select or Array#select.

level_2_employees = infoHash["employee"].select {|k| k["level"] == "2"}

This will return an array of employee info hashes according to your criteria. Be sure to put quotes around value for level

like image 120
Platinum Azure Avatar answered Sep 21 '22 18:09

Platinum Azure