Question

I'm loading the configuration from a YAML file.

I have a hash that looks like this: {:first=>{:abc=>[["one", "two", "three"]], :def => [["one", "two", "three"]]}, :second=>{:abc=>[["one", "two", "three"]]}}

But I would like to get:

{:first=>{:abc=>["one", "two", "three"], :def => ["one", "two", "three"]}, :second=>{:abc=>["one", "two", "three"]}}

I.e flatten the end arrays. Structure is not going to be any "deeper" than displayed here.

One-liner code is preferred.

Was it helpful?

Solution

This should work:

hash.each_value do |nested_hash|
  nested_hash.each_value do |array|
    array.flatten!
  end
end

or, in one-liner version:

hash.each_value { |nested_hash| nested_hash.each_value(&:flatten!) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top