DEV Community

loading...

Ruby Underscore

donaldong profile image Donald Dong ・1 min read

As a Ruby programmer, you probably have seen methods or blocks look like this:

def test(a, b, _); end
proc { |_, a| ... }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Not double underscore __ tho:

__ = 1
2
__ # returns 1
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

however, you cannot have

def test(x, x); end # this will cause an error
Enter fullscreen mode Exit fullscreen mode

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 🙂

Discussion (0)

pic
Editor guide