25

Just curious about it.

If you open the IRB and type _, you'll get nil as response:

irb(main):001:0> _
=> nil

And you can modify its value:

irb(main):002:0> _ = 'some value'
irb(main):003:0> _
=> "some value"

But if you create a new variable with _, its value is modified:

irb(main):004:0> foo_bar = 'other value'
irb(main):005:0> _
=> "other value"

Why? Is this a design decision?

Lucas Costa
  • 1,109
  • 9
  • 16
  • 1
    It's actually a handy feature. If you want to save the results of your last operation: `a = _`. I often use `irb` as a handy calculator, so you can easily chain things: `_ / 1e6` for example. – tadman Jan 04 '17 at 20:34
  • Some more fun meanings for the underscore are presented [Here](http://idiosyncratic-ruby.com/33-too-expressive.html#underscore-4-syntactical-meanings) such as a visual separator (`1_000_000`) or an ignored parameter `object.each {|_, v| ...}` – engineersmnky Jan 04 '17 at 20:43

2 Answers2

37

irb uses _ to refer to the value of last calculated expression. So you will see _ changed even if you don't use it in the previous line :)

Innot Kauker
  • 1,333
  • 1
  • 18
  • 30
17

Within irb, _ returns the result of the previous operation. So on opening a new irb session _ will equal nil as there was no previous operation

2.0.0p353 :001 > 4
 => 4 
2.0.0p353 :002 > 3 + _
 => 7 
ReggieB
  • 8,100
  • 3
  • 38
  • 46