0

我有以下代码:

>[['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.mappart替换[["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"]]为示例输出所示。

4

2 回答 2

5

使用splat 运算符

[
  ['string', 'User'], 
  *Foo.all.map { |c| ["number", c.name] }, 
  ['number', 'Average Time'],
]
于 2012-11-26T20:40:11.340 回答
1

试试这个

([['string', 'User']] + Foo.all.map {|c| ["number", c.name]} + [['number', 'Average Time']])
于 2012-11-26T20:20:00.203 回答