Question

I have an array of objects that have an array as attribute. I want to concatenate these attributes. I'm doing this:

result = []
objects.each { |obj| result.concat(obj.attr) }

which works but looks bad. I tried

objects.reduce(:attr)

which does not work. It's a Rails app, and I want to concatenate related items into a single array. I want this:

[{
  attr: [1,2]
},{
  attr: [3,4]
}]

to turn into this:

[1,2,3,4]
Was it helpful?

Solution

You need to use Array#map :-

result = objects.map { |obj| obj.attr }

If you want the result array to be flattened :-

result = objects.flat_map { |obj| obj.attr }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top