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 }
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]
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 }