Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior with '_' (underscore) in Ruby

Tags:

ruby

irb

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?

like image 658
Lucas Costa Avatar asked Jan 04 '17 19:01

Lucas Costa


2 Answers

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 :)

like image 114
Innot Kauker Avatar answered Oct 22 '22 08:10

Innot Kauker


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 
like image 39
11 revs, 10 users 40% Avatar answered Oct 22 '22 08:10

11 revs, 10 users 40%