Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>EDIT:</strong> In Ruby 2.1+, you can use <a href="http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-to_h">Array#to_h</a></p> <pre><code>pry(main)&gt; [[:a,:b],[:a,:c],[:c,:b]].to_h =&gt; {:a=&gt;:c, :c=&gt;:b} </code></pre> <p><strong>END EDIT</strong></p> <p>The public [] method on the Hash class accepts a key-value pair array and returns a hash with the first element of the array as key and the second as value.</p> <p>The last value in the key-value pair will be the actual value when there are key duplicates.</p> <pre><code>Hash[[[:a,:b],[:a,:c],[:c,:b]]] =&gt; {:a=&gt;:c, :c=&gt;:b} </code></pre> <p>This syntax is valid in 1.9.3+ ; I'm not sure about earlier Ruby versions (it's not valid in 1.8.7)</p> <p>ref: <a href="http://www.ruby-doc.org/core-2.1.0/Hash.html#method-c-5B-5D">http://www.ruby-doc.org/core-2.1.0/Hash.html#method-c-5B-5D</a></p> <p>Another interesting way of doing it would be using the inject method: (obviously the method above is more succinct and recommended for this specific problem)</p> <pre><code>[ [:a, :b], [:a, :c], [:c, :b] ].inject({}) { |memo, obj| memo[obj.first] = obj.last memo } =&gt; {:a=&gt;:c, :c=&gt;:b} </code></pre> <p>inject iterates over the enumerable, your array in this case, starting with the injected parameter, in this case the empty hash {}.</p> <p>For each object in the enumerable, the block is called with the variables memo and obj:</p> <ul> <li><p>obj is the current object in the array</p></li> <li><p>memo is the value that has been returned by your block's last iteration (for the first iteration, it's what you inject)</p></li> </ul>
 

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