【移行記事】【Ruby】配列の奇数番目と偶数番目の要素を分ける方法

※この記事ははてなブログからの移行記事です。

23:10:42

<pre class=“code lang-ruby” data-lang=“ruby” data-unlink>ary = [<span class=“synSpecial”>&quot;</span><span class=“synConstant”>A</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>B</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>C</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>D</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>E</span><span class=“synSpecial”>&quot;</span>]ary.each_slice(<span class=“synConstant”>2</span>).map { |<span class=“synIdentifier”>a</span>, <span class=“synIdentifier”>b</span>| [a, b] }.transpose<span class=“synComment”># =&gt; [ [ &quot;A&quot;, &quot;C&quot;, &quot;E&quot; ], [ &quot;B&quot;, &quot;D&quot;, nil ] ]</span></pre>

<code>each_slice</code>と<code>transpose</code>を使って、奇数番目の要素と偶数番目の要素を分ける。

<pre class=“code lang-ruby” data-lang=“ruby” data-unlink>ary.each_slice(<span class=“synConstant”>2</span>).map.to_a.transpose</pre>

本当はこう書きたかったけど、こうすると<code>transpose</code>前の状態が

<pre class=“code lang-ruby” data-lang=“ruby” data-unlink>[ [ <span class=“synSpecial”>&quot;</span><span class=“synConstant”>A</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>B</span><span class=“synSpecial”>&quot;</span> ], [ <span class=“synSpecial”>&quot;</span><span class=“synConstant”>C</span><span class=“synSpecial”>&quot;</span>, <span class=“synSpecial”>&quot;</span><span class=“synConstant”>D</span><span class=“synSpecial”>&quot;</span> ], [ <span class=“synSpecial”>&quot;</span><span class=“synConstant”>E</span><span class=“synSpecial”>&quot;</span> ] ]</pre>

となってしまい、数が合わず<code>transpose</code>でエラーになってしまう。(要素が偶数個ならうまくいく)