Ruby将可枚举数组展平为多个子阵列?

时间:2012-11-26 20:13:59

标签: ruby arrays enumerable

我有以下代码:

>[['string', 'User'], Foo.all.map {|c| ["number", c.name]}, ['number', 'Average Time']]
=> [["string", "User"], [["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"]], ["datetime", "Average Time"]]

我想做的是将传递的Foo可枚举数组简化为:

=> [["string", "User"], ["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"], ["datetime", "Average Time"]]

我尝试了下面的内容,但它并没有完全符合我的要求:

>[['string', 'User'], Foo.all.map {|c| ["number", c.name]}.flatten, ['number', 'Average Time']]
=> [["string", "User"], ["number", "Bar1", "number", "Bar2", "number", "Bar3"], ["datetime", "Average Time"]]

注意在测试时,您可以使用Fool.all.map替换[["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"]]部分,如示例输出所示。

2 个答案:

答案 0 :(得分:5)

使用splat operator

[
  ['string', 'User'], 
  *Foo.all.map { |c| ["number", c.name] }, 
  ['number', 'Average Time'],
]

答案 1 :(得分:1)

试试这个

([['string', 'User']] + Foo.all.map {|c| ["number", c.name]} + [['number', 'Average Time']])