Tintin81
Tintin81

Reputation: 10225

How to flatten nested hash in Ruby

What is the quickest way to flatten this hash:

REGIONS = {
  :au => {
    'Australian Capital Territory' => 'ACT',
    'New South Wales' => 'NSW',
  },
  :ca => {
    'Alberta' => 'AB',
    'British Columbia' => 'BC',
  }
}

so that the :au and :ca keys are removed and I get:

{
  'Australian Capital Territory' => 'ACT',
  'New South Wales' => 'NSW',
  'Alberta' => 'AB',
  'British Columbia' => 'BC'
}

I can merge hashes like this:

REGIONS[:au].merge(REGIONS[:ca])

But I can't do this here because the names of the hash keys will change frequently.

Upvotes: 3

Views: 2130

Answers (2)

sawa
sawa

Reputation: 168269

Here is a way to do it in a single iteration.

REGIONS.inject({}){|h, (_, e)| h.merge(e)}

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

REGIONS.values.reduce(&:merge)

Upvotes: 9

Related Questions