Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby use case for nil, equivalent to Python None or JavaScript undefined

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.

like image 676
Claudiu Avatar asked Oct 07 '10 17:10

Claudiu


People also ask

Why does Ruby use nil?

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.

Is nil object 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.

What is nil in Ruby on Rails?

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.


1 Answers

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 # ""
like image 67
tokland Avatar answered Oct 31 '22 17:10

tokland