Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby why does nil.id return 4?

Tags:

ruby

This is has been bugging me for quite some time.

>> nil.id (irb):2: warning: Object#id will be deprecated; use Object#object_id => 4 

Why would nil.id be 4? (or nil.object_id if you want to be picky about deprecations)

like image 274
epochwolf Avatar asked Feb 16 '09 14:02

epochwolf


People also ask

What does nil do in Ruby?

nil is a special Ruby data type that means "nothing". It's equivalent to null or None in other programming languages.

Does Ruby return nil by default?

By default methods in Ruby are empty, and an empty method returns, by default, nil.

How do you know if a Ruby is nil?

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 the same as null Ruby?

nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.


1 Answers

This is because nil is an object created when the language initializes, and that object's id happens to always be 4.

For more information about why the id happens to be 4, see this blog post.

like image 54
dagvl Avatar answered Sep 23 '22 17:09

dagvl