Ruby range.reduce with hash accumulator
<p>I have this method</p>



<pre><code>def heights
  (60..68).reduce({}) { |h, i| h.merge!( { %(#{i/12}'#{i%12}") =&gt; i } ) }
end
</code></pre>

<p>it returns a hash of heights</p>

<pre><code>{
  "5'0\"" =&gt; 60, "5'1\"" =&gt; 61, "5'2\"" =&gt; 62,
  "5'3\"" =&gt; 63, "5'4\"" =&gt; 64, "5'5\"" =&gt; 65,
  "5'6\"" =&gt; 66, "5'7\"" =&gt; 67, "5'8\"" =&gt; 68
}
</code></pre>

<p>That's what I want. However, I don't like using the <code>merge!</code> method. I'd much rather use the <code>hash[key] = value</code> syntax for assignment:</p>

<pre><code>def heights
  (60..68).reduce({}) { |h, i| h[%(#{i/12}'#{i%12}")] = i }
end
</code></pre>

<p>But this code throws errors. I know that with reduce, in your pipes you can name your accumulator and element.</p>

<p>I also understand that</p>

<pre><code>sum = 0
(1..5).each { |i| sum += i }
</code></pre>

<p>is equivalent to</p>

<pre><code>(1..5).reduce(0) { |sum, i| sum + i }
</code></pre>

<p>So why doesn't this</p>

<pre><code>hash = {}
(1..5).each { |i| hash[i.to_s] = i }
</code></pre>

<p>work the same as</p>

<pre><code>(1..5).reduce({}) { |hash, i| hash["#{i}"] = i }
</code></pre>