Hash into grouped array

2019-05-10 18:24发布

im not very experienced in ruby, so im struggling to format a piece of data.

I have this hash, wich contains some keys that have the same value, ex:

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

I'm trying to turn this into, an array containing the keys grouped by the values

 [["key","key4"],["key2","key5"],["key3"]]

Any help would be appreciated.

标签: ruby arrays hash
3条回答
三岁会撩人
2楼-- · 2019-05-10 18:29
hash.group_by{|k,v| v}.map{|k,v| v.reduce([]){|res,n| res << n.first}}
查看更多
来,给爷笑一个
3楼-- · 2019-05-10 18:32
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"]]
查看更多
来,给爷笑一个
4楼-- · 2019-05-10 18:51
new_hash = {}
hash.each do |key, value|
  new_hash[value] ||= []
  new_hash[value] << key
end
array = new_hash.values # => [["key", "key4"], ["key2", "key5"], ["key3"]]
查看更多
登录 后发表回答