Returning Multiple Values From Map
Asked Answered
L

2

20

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?

Laevo answered 14/9, 2013 at 9:27 Comment(2)
Can you give an example input and output to let us know,what you are expecting. It helps us to help you ...Embosser
You would never use map() in your code there because each() would suffice. Your code unnecessarily creates an array that you then throw away.Bronwen
H
29

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]
Honebein answered 14/9, 2013 at 9:28 Comment(0)
B
0

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]
Bronwen answered 14/9, 2013 at 10:52 Comment(2)
I believe flat_map is more efficient (because you don't need to iterate over the whole array twice)Cohleen
It is not the same thing if your map return arrays like [1, 2, [1, 2, 3]]Explicit

© 2022 - 2024 — McMap. All rights reserved.