Pietro
Pietro

Reputation: 1836

ruby hash, group_by value

I want to group an hash by values.

Example:

start_with_hash = { "10:00" => "2014-10-10", "11:00" => "2014-10-10", "11:30" => "2014-10-10, 2014-10-11", "12:00" => "2014-10-11"}


end_with_hash = {"10:00, 11:00" => "2014-10-10", "11:30" => "2014-10-10, 2014-10-11", "12:00" => "2014-10-11" }

Upvotes: 0

Views: 487

Answers (3)

levinalex
levinalex

Reputation: 5969

not exactly what you asked for:

class Hash
  # make a new hash with the existing values as the new keys
  # - like #rassoc for each existing key
  # - like invert but with *all* keys as array
  #
  #   {1=>2, 3=>4, 5=>6, 6=>2, 7=>4}.flip #=> {2=>[1, 6], 4=>[3, 7], 6=>[5]}
  #
  def flip
    inject({}) { |h, (k,v)| h[v] ||= []; h[v] << k; h }
  end
end

start_with_hash.flip 
#=> {"2014-10-10"=>["10:00", "11:00"], 
     "2014-10-10, 2014-10-11"=>["11:30"], 
     "2014-10-11"=>["12:00"]}

Upvotes: 0

nikolayp
nikolayp

Reputation: 17949

merged_hash = start_with_hash.merge(end_with_hash){|key, oldval, newval| oldval }

more information here http://ruby-doc.org/core-2.1.0/Hash.html#method-i-merge

=> {
         "10:00" => "2014-10-10",
         "11:00" => "2014-10-10",
         "11:30" => "2014-10-10, 2014-10-11",
         "12:00" => "2014-10-11",
  "10:00, 11:00" => "2014-10-10"
}

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118299

I would do as below :

start_with_hash = { "10:00" => "2014-10-10", "11:00" => "2014-10-10", "11:30" => "2014-10-10, 2014-10-11", "12:00" => "2014-10-11"}
Hash[start_with_hash.group_by(&:last).map{|k,v| [v.map(&:first).join(","),k] }]

Upvotes: 3

Related Questions