"value1", "key2" => "value2", "key3"-6ren">
gpt4 book ai didi

ruby - 散列成分组数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:32 25 4
gpt4 key购买 nike

我对ruby不是很有经验,所以我正在努力格式化一段数据。

我有这个散列,其中包含一些具有相同值的键,例如:

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

我想把它变成一个包含按值分组的键的数组

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

最佳答案

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

关于ruby - 散列成分组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9557485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com