从地图返回多个值

Und*_*ion 15 ruby arrays each map enumerator

有办法吗?

a = b.map{ |e| #return multiple elements to be added to a }
Run Code Online (Sandbox Code Playgroud)

而不是为每个要添加的迭代返回单个对象,a可以返回多个对象.

我目前正在实现这一目标:

a = []
b.map{ |e| a.concat([x,y,z]) }
Run Code Online (Sandbox Code Playgroud)

有没有办法在单行中进行此操作而无需事先声明a = []

fal*_*tru 23

使用 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]
Run Code Online (Sandbox Code Playgroud)