In Ruby, how _ | _?

I am confused about how puts _|_

Ruby works. If you introduce a variable then call this statement

3
puts _|_

      

you will get the name of the variable followed by nil

 3
 => nil

      

However, if you type it again, you get false

puts _|_
=> false

      

It doesn't look like one of those Perl-like variables that start with a dollar sign.

What does this strange symbol mean in the world and how does it work?

+3


source to share


4 answers


An underscore in the console (IRB or pry) means the result of the previous command. So

3
=> 3
puts _|_
3
=> nil

      

Here the above statement puts

becomes equivalent to

puts 3 <bit-wise or> 3

      



which puts 3|3

is puts 3

.

Since it puts

returns nil

, when you iterate puts _|_

it becomes

puts nil|nil

      

... which is equal puts false

.

+6


source


_

is a special ruby ​​variable, it is used to get the result of the previous expression.

irb(main):030:0> 3
=> 3
irb(main):031:0> _
=> 3
irb(main):032:0> _.to_s
=> "3"
irb(main):033:0> _
=> "3"

      



A ruby ​​variable whose name begins with a lowercase letter (az) or underscore (_) is a local variable or method call. Uninitialized instance variables are nil.

irb(main):001:0> _
=> nil
irb(main):002:0> _ | _
=> false
irb(main):003:0> nil | nil
=> false

      

+3


source


The ruby _

is a valid ID.

In IRB

_

contains the value of the last expression.

2.1.5 :001 > 100
 => 100
2.1.5 :002 > _
 => 100

      

+3


source


_

is a special ruby ​​variable, this variable stores the value of the previous expression / command, so when you do:

1.9.3-p0 :043 > 3
 => 3

      

'_' contains the value 3, since the return value of the previous expression is 3. When you use puts like below:

1.9.3-p0 :045 > puts _|_
3
 => nil

      

its return value is nil.Next time when you execute | as shown below:

1.9.3-p0 :049 > _|_
 => false

      

it returns false because it is similar to the below expression:

1.9.3-p0 :050 > nil|nil
 => false

      

that's why puts | returns false.

0


source







All Articles