I watched this video. Why is a = a
evaluated to nil
if a
is not defined?
a = a # => nil b = c = q = c # => nil
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.
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.
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).
Well, nil is a special Ruby object used to represent an “empty” or “default” value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With