문제

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]
도움이 되었습니까?

해결책

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 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top