散列成分组数组

时间:2012-03-04 18:09:22

标签: ruby arrays hash

我对ruby没有太多经验,所以我很难格式化一段数据。

我有这个哈希,它包含一些具有相同值的键,例如:

{"key" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value1", "key5" => "value2" ..}

我正在尝试将其转换为包含按值

分组的键的数组
 [["key","key4"],["key2","key5"],["key3"]]

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:6)

new_hash = {}
hash.each do |key, value|
  new_hash[value] ||= []
  new_hash[value] << key
end
array = new_hash.values # => [["key", "key4"], ["key2", "key5"], ["key3"]]

答案 1 :(得分:3)

hash = {
  "key" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" => "value1",
  "key5" => "value2"
}

hash.group_by { |key, value| value }.values.map { |pairs| pairs.map &:first }

# => [["key", "key4"], ["key2", "key5"], ["key3"]]

答案 2 :(得分:0)

hash.group_by{|k,v| v}.map{|k,v| v.reduce([]){|res,n| res << n.first}}