Chris F
Chris F

Reputation: 16685

How do I collect nested hash values into an array in ruby?

Say I have the following hash.

my_hash = {
  'array1' => %w[
    value1
    value2
  ],
  'array2' => %w[
    value3
    value4
  ]
}

How do I make an array that looks like

my_array = %w[value1 value2 value3 valuu4]

Upvotes: 1

Views: 522

Answers (2)

dug
dug

Reputation: 2335

my_array = my_hash.values.flatten
=> ["value1", "value2", "value3", "value4"]

Upvotes: 3

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Flatten Hash Values

Use Hash#values to collect the values from your Hash, and then use Array#flatten to turn the result into a single Array rather than one containing nested arrays. For example:

my_hash.values.flatten
#=> ["value1", "value2", "value3", "value4"]

Upvotes: 1

Related Questions