DEV Community

Cover image for The Useful & Hidden '_' Command In IRB
Edwin Mak
Edwin Mak

Posted on • Edited on

The Useful & Hidden '_' Command In IRB

Introduction (TLDR sorta)

As a developer, I am alway seeking for tools and tricks that allow me to be more efficient while working on projects. As a result, I've adopted some lesser known ruby interactive shell command. One of which is the underscore or _. I found that this command when applied can be super beneficial and boost your productivity!

The underscore simply gives you the return value of the last evaluation made in the console. I find this especially useful in the event I forget to assign the output of a block of code or when I perform a query via Rails that I’d rather not run again. Let me show you what I mean:

Example Use Case

Example

Above is a screenshot detailing an example use case. In that example, I evaluated a block of code with a 5-second pause (to simulate a slow operation) without assigning it to the variable animal. Nothing to worry about, you can just use the underscore to avoid having to execute that code again!

Another fairly common situation were you might benefit from using the _ method is when you run a query in Rails... but forgot to assign it to a variable!

Conclusion

The underscore is a useful tool to use when you are working in the ruby interactive shell. It may not seem like a lot of time to just re-run slow code… but it does add up!

What other kinds of hidden ruby tricks are there out? Please comment on this post if you know any and are in a charitable mood.

Top comments (5)

Collapse
 
sijiadavis profile image
CeliaD

another thing I find useful when working with Rails console is the sandbox mode rails console --sandbox. When starting the Rails console in sandbox mode, the entire session will be wrapped in a transaction, and gets rolled back when you exit the console. This is nice when we want to mutate some records for testing purpose and not mess up our development/production data.

Collapse
 
edwinthinks profile image
Edwin Mak

Ahh nice! I didn't know you could do that!

Collapse
 
keithrbennett profile image
Keith Bennett

I always thought of _ more of a variable (like Ruby's global or thread-global variables such as $?) than a method or expression. I guess it's probably implemented as a method though.

Collapse
 
detunized profile image
Dmitry Yakimenko

It's not a Ruby method, it's an irb (Ruby interactive prompt or REPL) shortcut for the result of the last evaluated expression. _ doesn't have such a meaning in a regular Ruby program.

Collapse
 
edwinthinks profile image
Edwin Mak

Hey Dmitry. Yep you are absolutely right! The _ expression cannot be used in regular Ruby programs. I'll update the post to add a clarifying statement about this point. Thanks!