Home > Enterprise >  How can I group hash contents based on key starts_with?
How can I group hash contents based on key starts_with?

Time:10-22

I have a hash that currently looks like this:

{
  "prefix1_key1": [a, b],
  "prefix1_key2": [c, d],
  "prefix2_key1": [e, f],
  "prefix3_key1": [g, h]
}

And I would want to transfer this into:

{
  "prefix1": [a, b, c, d],
  "prefix2": [e, f],
  "prefix3": [g, h]
}

Is there any clean way that I can do this?

CodePudding user response:

Here is a working solution:

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

CodePudding user response:

Input

hash = {
  "prefix1_key1": ['a', 'b'],
  "prefix1_key2": ['c', 'd'],
  "prefix2_key1": ['e', 'f'],
  "prefix3_key1": ['g', 'h']
}

Code

p hash.group_by { |k, v| k.to_s.split("_").first }
      .transform_values { |x| x.flat_map(&:pop) }

Output

{"prefix1"=>["a", "b", "c", "d"], "prefix2"=>["e", "f"], "prefix3"=>["g", "h"]}
  • Related