Steven Kwok Steven Kwok - 6 months ago 12
Ruby Question

How to organize hashes by property

Here is the hashes that will be processed:

{
"flatiron school bk" => {
:location => "NYC"
},
"flatiron school" => {
:location => "NYC"
},
"dev boot camp" => {
:location => "SF"
},
"dev boot camp chicago" => {
:location => "Chicago"
},
"general assembly" => {
:location => "NYC"
},
"Hack Reactor" => {
:location => "SF"
}
}


I need to organize these hashes by location, like this:

{ "NYC"=>["flatiron school bk", "flatiron school", "general assembly"],
"SF"=>["dev boot camp", "Hack Reactor"],
"Chicago"=>["dev boot camp chicago"]}
}

Answer

You can use each_with_object to combine in into new hash:

hash.each_with_object({}) do |(name, data), res|
  (res[data[:location]] ||= []) << name
end

Explanation:

each_with_object Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

In this case name and data is key and value of each element in given hash. In (res[data[:location]] ||= []) << name you get location, create array in result hash for given location (if it doesn't exist), then put key of input hash to it.

Comments