Stefan Stefan - 1 year ago 90
Ruby Question

How to efficiently concatenate multiple arrays in Ruby?

I just wanted to concatenate multiple arrays in Ruby and couldn't find a satisfying way to do so.

Example input:

foo = [1, 2, 3]
bar = [4, 5, 6]
baz = [7, 8, 9]

Expected result: (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

  • foo + bar + baz
    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
    [1, 2, 3, 4, 5, 6]
    that is thrown away after the whole operation. As noted in the documentation:

    repeated use of
    on arrays can be quite inefficient

  • [*foo, *bar, *baz]
    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].flatten(1)
    seems to be even worse than the above, performance wise.

  • [].concat(foo).concat(bar).concat(baz)
    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?

Max Max
Answer Source

If you've already determined that multiple concatenation is the fastest method, you can write it nicer using reduce:

[foo, bar, baz].reduce([], :concat)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download