MxLDevs
MxLDevs

Reputation: 19526

Collect a hash of arrays in ruby

h = {1=>[1,2,3], 2=>[4,5,6]}
new_arr = []
h.each_value {|arr|
  new_arr.concat(arr)
}

This works, but what's a more ruby-like way to do it?

All values are arrays but the elements of each array should not be modified.

Upvotes: 1

Views: 779

Answers (4)

Andrew Grimm
Andrew Grimm

Reputation: 81530

Slightly cryptic

h.flat_map(&:last)

Slightly verbose

h.flat_map{|_, value| value}

Upvotes: 1

utwang
utwang

Reputation: 1484

If you want to get the array of hash value, use Hash#values.

new_arr = h.values

Upvotes: 0

d11wtq
d11wtq

Reputation: 35308

You can use reduce:

h.values.reduce(&:+)

Upvotes: 4

kakutani
kakutani

Reputation: 183

How's about this?

h.values.flatten

Upvotes: 10

Related Questions