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?
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.
We can use the values method to return all the values of a hash in Ruby.
Use #each to iterate over a hash.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With