我想按值对散列进行分组。
示例:
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" }发布于 2014-01-16 13:42:51
以下是我要做的:
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] }]发布于 2014-01-16 13:43:59
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"
}发布于 2014-01-16 14:02:01
不完全是你要求的:
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"]}https://stackoverflow.com/questions/21163361
复制相似问题