Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Multiple Values From Map

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?

like image 231
Undistraction Avatar asked Sep 14 '13 09:09

Undistraction


People also ask

Can map function return multiple values?

The mapper function passed to map() returns a single value for a single input. The function passed to flatmap() operation returns multiple numbers of values as the output.

How do I return multiple items on a map?

To return multiple items, use the flatMap() function… A better approach to returning multiples from an array is by using the flatMap() function.

Can you have multiple return values?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values.

Does map return an array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .


1 Answers

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]
like image 108
falsetru Avatar answered Sep 22 '22 03:09

falsetru