Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `a = a` `nil` in Ruby?

I watched this video. Why is a = a evaluated to nil if a is not defined?

a = a # => nil b = c = q = c # => nil 
like image 582
Brian Hsu Avatar asked Jan 18 '12 09:01

Brian Hsu


People also ask

What does nil mean in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

How do you handle nil in Ruby?

In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.

How do you check nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

Is nil empty Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value.


1 Answers

Ruby interpreter initializes a local variable with nil when it sees an assignment to it. It initializes the local variable before it executes the assignment expression or even when the assignment is not reachable (as in the example below). This means your code initializes a with nil and then the expression a = nil will evaluate to the right hand value.

a = 1 if false a.nil? # => true 

The first assignment expression is not executed, but a is initialized with nil.

You can find this behaviour documented in the Ruby assignment documentation.

like image 75
Aliaksei Kliuchnikau Avatar answered Sep 21 '22 00:09

Aliaksei Kliuchnikau