문제

Is there a way to do:

a = b.map{ |e| #return multiple elements to be added to a }

Where rather than returning a single object for each iteration to be added to a, multiple objects can be returned.

I'm currently achieving this with:

a = []
b.map{ |e| a.concat([x,y,z]) }

Is there a way to this in a single line without having to declare a = [] up front?

도움이 되었습니까?

해결책

Use Enumerable#flat_map

b = [0, 3, 6]
a = b.flat_map { |x| [x, x+1, x+2] }
a # => [0, 1, 2, 3, 4, 5, 6, 7, 8]

다른 팁

Use Enumerable#flat_map

Which is probably not much different than:

p [1, 2, 3].map{|num| [1, 2, 3]}.flatten 

--output:-
[1, 2, 3, 1, 2, 3, 1, 2, 3]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top