如何根据键 starts_with 对散列内容进行分组?
How can I group hash contents based on key starts_with?
我有一个目前看起来像这样的散列:
{
"prefix1_key1": [a, b],
"prefix1_key2": [c, d],
"prefix2_key1": [e, f],
"prefix3_key1": [g, h]
}
我想将其转移到:
{
"prefix1": [a, b, c, d],
"prefix2": [e, f],
"prefix3": [g, h]
}
有什么干净的方法可以做到这一点吗?
这是一个可行的解决方案:
hash = {
"prefix1_key1": [a, b],
"prefix1_key2": [c, d],
"prefix2_key1": [e, f],
"prefix3_key1": [g, h]
}
hash.each_with_object({}) do |ary, result|
key = ary[0].to_s.split('_')[0]
(result[key] ||= []).concat(ary[1])
end
输入
hash = {
"prefix1_key1": ['a', 'b'],
"prefix1_key2": ['c', 'd'],
"prefix2_key1": ['e', 'f'],
"prefix3_key1": ['g', 'h']
}
代码
p hash.group_by { |k, v| k.to_s.split("_").first }
.transform_values { |x| x.flat_map(&:pop) }
输出
{"prefix1"=>["a", "b", "c", "d"], "prefix2"=>["e", "f"], "prefix3"=>["g", "h"]}
我有一个目前看起来像这样的散列:
{
"prefix1_key1": [a, b],
"prefix1_key2": [c, d],
"prefix2_key1": [e, f],
"prefix3_key1": [g, h]
}
我想将其转移到:
{
"prefix1": [a, b, c, d],
"prefix2": [e, f],
"prefix3": [g, h]
}
有什么干净的方法可以做到这一点吗?
这是一个可行的解决方案:
hash = {
"prefix1_key1": [a, b],
"prefix1_key2": [c, d],
"prefix2_key1": [e, f],
"prefix3_key1": [g, h]
}
hash.each_with_object({}) do |ary, result|
key = ary[0].to_s.split('_')[0]
(result[key] ||= []).concat(ary[1])
end
输入
hash = {
"prefix1_key1": ['a', 'b'],
"prefix1_key2": ['c', 'd'],
"prefix2_key1": ['e', 'f'],
"prefix3_key1": ['g', 'h']
}
代码
p hash.group_by { |k, v| k.to_s.split("_").first }
.transform_values { |x| x.flat_map(&:pop) }
输出
{"prefix1"=>["a", "b", "c", "d"], "prefix2"=>["e", "f"], "prefix3"=>["g", "h"]}