How to efficiently concatenate multiple arrays in Ruby?
<p>I just wanted to concatenate multiple arrays in Ruby and couldn't find a satisfying way to do so.</p>

<p><strong>Example input:</strong></p>

<pre><code>foo = [1, 2, 3]
bar = [4, 5, 6]
baz = [7, 8, 9]
</code></pre>

<p><strong>Expected result:</strong> (without modifying the existing arrays)</p>

<pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>

<p>My actual arrays are <em>much</em> larger, so I'm interested in an efficient solution. There may also be more than three arrays, so a short syntax is preferred.</p>

<h3>What I have tried so far</h3>

<ul>
<li><p><code>foo + bar + baz</code> is the obvious one, it's concise and clear. But it is evaluated as <code>(foo + bar) + baz</code>. In other words: it creates an intermediate array <code>[1, 2, 3, 4, 5, 6]</code> that is thrown away after the whole operation. As noted in the <a href="http://ruby-doc.org/core-2.3.1/Array.html#method-i-2B" rel="noreferrer">documentation</a>:</p>

<blockquote>
  <p>repeated use of <code>+=</code> on arrays can be quite inefficient</p>
</blockquote></li>
<li><p><code>[*foo, *bar, *baz]</code> basically inlines the elements which is not very efficient for large arrays, either. It also looks more like a hack to me.</p></li>
<li><p><code>[foo, bar, baz].flatten(1)</code> seems to be even worse than the above, performance wise.</p></li>
<li><p><code>[].concat(foo).concat(bar).concat(baz)</code> is the fastest, but it looks cumbersome and it needs multiple method invocations.</p></li>
</ul>

<p>Shouldn't there be a simple class method for such a basic task? Something like:</p>

<pre><code>Array.concat(foo, bar, baz)
</code></pre>

<p>Am I missing something obvious?</p>