Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Nil and Zero

Tags:

ruby

What's the science behind the fact that the to_i method in Ruby's NilClass instances returns zero? Returning nil or raising an exception would not be more logical?

like image 444
Henry Mazza Avatar asked Jun 17 '11 18:06

Henry Mazza


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.

Is 0 true or false in Ruby?

Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

What is the difference between nil and empty in Ruby?

nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else. empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings.

How do I check if a variable is nil in Ruby?

That's the easy part. 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).


1 Answers

It fits the Ruby philosophy of permissiveness (as opposed to, for example, the strictness of Python):

nil.to_i #=> 0 
"".to_i #=> 0
"123hello".to_i #=> 123
"hello".to_i #=> 0

As noted by Zabba, you can use Kernel#Integer(string) for strict conversion.

like image 84
tokland Avatar answered Sep 21 '22 00:09

tokland