Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby: setting a new hash with an array of keys/values
    text
    copied!<p>I'm learning Ruby via RubyMonk. In the solution to the <a href="http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/33-advanced-arrays/lessons/97-array-alternative-uses#solution4269" rel="nofollow">waiter robot problem</a>, there's a line of code that creates a new hash using an array:</p> <pre><code>o = Hash[*order] </code></pre> <p>given</p> <pre><code>order = [:table, 1, :sandwich, "denver", :drink, "mango shake"] </code></pre> <p>I understand what's being done here and how the splat operator works. However, I'm confused about the syntax for creating this hash. <a href="http://ruby-doc.org/core-2.0/Hash.html#method-c-5B-5D" rel="nofollow">RubyDoc</a> says that <code>::[]</code> is really the method being called, so I was able to determine that <code>o = Hash::[](*order)</code> is the same thing. But why can this be shortened to just <code>Hash[*order]</code>? Is this a special construct that gets interpreted by the parser, or is there another reason? Along the same lines, why don't any of the following work?</p> <pre><code>o = Hash.new o.[](*order) </code></pre> <p>or</p> <pre><code>o = Hash.new o[*order] </code></pre> <p>or even something like <code>o = {}[*order]</code></p> <p>I know these <em>shouldn't</em> work; I'm just not sure why. I think I'm confused by the usage of <code>Hash[*order]</code> without first instantiating a hash with <code>Hash.new</code>. Is this an example of the difference between class methods and instance methods?</p> <p>(As a side note, it seems to me that <code>o = {*order}</code> should work, but it doesn't.)</p> <p>Can someone explain what's going on here, and if there are alternate ways to add values from an array into a hash?</p>
 

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