Note that there are some explanatory texts on larger screens.

plurals
  1. POWhere and how is the _ (underscore) variable specified?
    primarykey
    data
    text
    <p>Most are aware of <code>_</code>’s special meaning in IRB as a holder for last return value, but that is <em>not</em> what I'm asking about here.</p> <p>Instead, I’m asking about <code>_</code> when used as a variable name in plain-old-Ruby-code. Here it appears to have special behavior, akin to a “don't care variable” (à la <a href="http://www.cse.unsw.edu.au/~billw/prologdict.html#dontcare" rel="nofollow noreferrer">Prolog</a>). Here are some useful examples illustrating its unique behavior:</p> <pre><code>lambda { |x, x| 42 } # SyntaxError: duplicated argument name lambda { |_, _| 42 }.call(4, 2) # =&gt; 42 lambda { |_, _| 42 }.call(_, _) # NameError: undefined local variable or method `_' lambda { |_| _ + 1 }.call(42) # =&gt; 43 lambda { |_, _| _ }.call(4, 2) # 1.8.7: =&gt; 2 # 1.9.3: =&gt; 4 _ = 42 _ * 100 # =&gt; 4200 _, _ = 4, 2; _ # =&gt; 2 </code></pre> <p>These were all run in Ruby directly (with <code>puts</code>s added in)—not IRB—to avoid conflicting with its additional functionality.</p> <p>This is all a result of my own experimentation though, as I cannot find any documentation on this behavior anywhere (admittedly it's not the easiest thing to search for). Ultimately, I'm curious how all of this works internally so I can better understand exactly what is special about <code>_</code>. So I’m asking for references to documentation, and, preferably, the Ruby source code (and perhaps <a href="http://rubyspec.org/" rel="nofollow noreferrer">RubySpec</a>) that reveal how <code>_</code> behaves in Ruby.</p> <p><sub><em>Note: most of this arose out of <a href="https://stackoverflow.com/questions/9557485/hash-into-grouped-array/9557589#comment12116685_9557589">this discussion</a> with <a href="https://stackoverflow.com/users/916657/niklas-b">@Niklas B.</a></em></sub></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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