As a Ruby programmer, you probably have seen methods or blocks look like this:
def test(a, b, _); end
proc { |_, a| ... }
But what exactly is this _
thingy, and how is it special?
Underscore is a valid object identifier
Yes, you can access, and assign values to _
and you are also able to use it as a method name.
def a(_); puts _; end # a(3) prints 3
Yet it does not work exactly the way you might expect in IRB, because it’s explicitly configured to return the last used value in the Ruby console
_ = 1
2
_ # returns 2, not 1
Not double underscore __
tho:
__ = 1
2
__ # returns 1
Underscore is treated a bit differently than other object identifiers
You could have (>= Ruby 1.9)
def test(_, _); end
def test(__, __); end
def test(__x, __x); end
however, you cannot have
def test(x, x); end # this will cause an error
Ruby explicitly allows duplicate parameter names when they’re made of underscore _
.
It is most common for people to use _
to represent unused parameters (placeholders), yet as the examples above showed, you can use other symbols to avoid “unused var” warnings too 🙂
Top comments (0)