ruby hash,group_by value

时间:2014-01-16 13:38:32

标签: ruby-on-rails ruby

我想按值对哈希进行分组。

示例:

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" }

3 个答案:

答案 0 :(得分:4)

我会这样做:

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] }]

答案 1 :(得分:0)

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

此处提供更多信息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"
}

答案 2 :(得分:0)

不完全是你要求的:

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"]}