0

I have the following code:

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

What I would like to do is flatten the passed Foo enumerable array into simply:

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

I tried the following but it didn't quite do what I wanted:

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

Note when testing you can replace Fool.all.map part with [["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"]] as demonstrated with the example output.

Noz
  • 6,216
  • 3
  • 47
  • 82
  • Excuse me? Who voted down my question as not a real question? Where exactly is the ambiguity? I specified what I wanted, what I was doing, and what I was expecting - do you want an autobiography perhaps? – Noz Nov 26 '12 at 20:20
  • 5
    It would be more convenient trying your example in `irb/pry` if you replaced `Foo.all` by some fake data. (I'm not who downvoted you, but anyway) – hs- Nov 26 '12 at 20:29
  • Good point, certainly does NOT warrant a vote to close @ the down voter – Noz Nov 26 '12 at 20:36

2 Answers2

5

With the splat operator:

[
  ['string', 'User'], 
  *Foo.all.map { |c| ["number", c.name] }, 
  ['number', 'Average Time'],
]
tokland
  • 66,169
  • 13
  • 144
  • 170
  • 3
    `*` explodes an array in place, basically removing the surrounding `[...]`. Think of it as "take the guts of this array and stick them here". In other languages it'd be "use the contents this pointer references", so thinking of it that way might help. – the Tin Man Nov 26 '12 at 21:00
1

Try this

([['string', 'User']] + Foo.all.map {|c| ["number", c.name]} + [['number', 'Average Time']])
stupied4ever
  • 353
  • 3
  • 7
  • 1
    This concatenates the the enumerable array into the first and last elements of the array like so `=> ["string", "User", ["number", "Bar1"], ["number", "Bar2"], ["number", "Bar3"], "number", "Average Time"] ` – Noz Nov 26 '12 at 20:32