How does Ruby's nil
manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined
pops up even more because you can't specify default arguments at all. Can you give an example of how RubyNone
pops up and how it's dealt with?
I'm not looking for just an example using nil
. Preferably it would be a real code snippet which had to use nil
for some reason or other.
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
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, 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.
Ruby's nil and Python's None
are equivalent in the sense that they represent the absence of a value. However, people coming from Python may find some behavior surprising. First, Ruby returns nil
in situations Python raises an exception:
Accessing arrays and hashes:
[1, 2, 3][999] # nil. But [].fetch(0) raises an IndexError
{"a" => 1, "b" => 2}["nonexistent"] # nil. But {}.fetch("nonexistent") raises an IndexError
Instance instance variables:
class MyClass
def hello
@thisdoesnotexist
end
end
MyClass.new.hello #=> nil
The second remarkable fact is that nil
is an object with lots of methods. You can even convert it to an integer, float or string:
nil.to_i # 0
nil.to_f # 0.0 # But Integer(nil) or Float(nil) raise a TypeError.
nil.to_s # ""
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