I just wanted to concatenate multiple arrays in Ruby and couldn't find a satisfying way to do so.
foo = [1, 2, 3]
bar = [4, 5, 6]
baz = [7, 8, 9]
(without modifying the existing arrays)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
My actual arrays are much
larger, so I'm interested in an efficient solution. There may also be more than three arrays, so a short syntax is preferred.
What I have tried so far
is the obvious one, it's concise and clear. But it is evaluated as
foo + bar + baz
. In other words: it creates an intermediate array
(foo + bar) + baz
that is thrown away after the whole operation. As noted in the documentation:
[1, 2, 3, 4, 5, 6]
repeated use of
on arrays can be quite inefficient
basically inlines the elements which is not very efficient for large arrays, either. It also looks more like a hack to me.
[*foo, *bar, *baz]
seems to be even worse than the above, performance wise.
[foo, bar, baz].flatten(1)
is the fastest, but it looks cumbersome and it needs multiple method invocations.
Shouldn't there be a simple class method for such a basic task? Something like:
Array.concat(foo, bar, baz)
Am I missing something obvious?