This was the tip of the week in the April 8, 2021 Ruby Weekly Newsletter.

Often, when working in an IRB console, I’ll realize only after running a command that I didn’t store the result in a variable but I’d like to access it. Thankfully, IRB has _ to allow us to access our previous result:

irb> some.expensive_method
=> :some_result

# We can access the result without having
# to re-run the expensive method using _
irb> variable_to_store_result = _
=> :some_result

But did you know IRB also gives us the ability to access evaluations prior to the most recent one?

We have to configure this ability explicitly by setting IRB.conf[:EVAL_HISTORY] to the number of results we’d like to store. We can add this snippet to our ~/.irbrc file and it will apply to every IRB console we open:

# This will allow us to access our previous
# 3 evaluations in an IRB console

Or, you can run this code within an already running IRB context:

IRB::CurrentContext().eval_history = 3
And then, once we've configured our eval history, we can access previous evaluations like this:

irb> this = "is just to demonstrate"
irb> how = :useful
irb> this_command = :can_be

# We'll see IRB.conf[:EVAL_HISTORY] number
# of the most recent results we've gotten
# if we use __
irb> __
1 "is just to demonstrate"
2 :useful
3 :can_be

# And we can access them by index
> __[2]
=> :useful

# And even store them as variables
> some_var = __[3]
=> :can_be

Note: In case it’s not clear, this feature uses a double underscore rather than a single one.

Hopefully this saves a little re-running of commands in IRB to store evaluations.