Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the ruby idiomatic way to set a hash entry to a array before appending to it?
    text
    copied!<p>I am trying to create a hash that has a key and an array of values associated with the key. So I was doing something like this</p> <pre><code> hash = Hash.new </code></pre> <p>and then later when I have a key I would do this</p> <pre><code> hash[key] &lt;&lt; new_thing </code></pre> <p>but this fails if hash[key] is nil , so I added this statement before trying to append the new_thing to the array.</p> <pre><code> hash[key] = Array.new unless hash[key] hash[key] &lt;&lt; new_thing </code></pre> <p>I thought I could eliminate the added statement by changing the definition of hash to</p> <pre><code>hash = Hash.new Array.new </code></pre> <p>but this does not work because each entry shares the same array, what I really need is this</p> <pre><code>hash = Hash.new { |h,k| h[k] = Array.new } </code></pre> <p>I know I am probably splitting hairs but, I am just curious, what would be the "ruby" way to do this?</p> <p><strong>EDIT:</strong> Ultimately what I ended up doing is using group_by. I realize it was not obvious from my question that I was trying to use this structure to group objects with the same property together in a hash. I am including this to encourage others that may find themselves using a similar structure for a similar purpose to check out <a href="http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-group_by" rel="nofollow">group_by</a></p> <pre><code>["A", 1, "b", 3].group_by { |i| i.class } =&gt; {String=&gt;["A", "b"], Fixnum=&gt;[1, 3]} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload