---
title: "Why the id of nil is 4 in Ruby"
description: "Discusses why the id of nil is 4 in Ruby. Why 4. Why not 3 or 5."
canonical_url: "https://www.bigbinary.com/blog/why-the-id-of-nil-is-4-in-ruby"
markdown_url: "https://www.bigbinary.com/blog/why-the-id-of-nil-is-4-in-ruby.md"
---

# Why the id of nil is 4 in Ruby

Discusses why the id of nil is 4 in Ruby. Why 4. Why not 3 or 5.

- Author: Neeraj Singh
- Published: June 23, 2008
- Categories: Ruby

_Following code was tested with ruby 1.8.7 and Rails 2.3_ .

While developing rails application you have must seen this

```plaintext

Called id for nil, which would mistakenly be 4 — if you really
wanted the id of nil, use object_id

```

We all know that this message is added by Rails and it is called `whiny nil` .
If you open your `config/development.rb` file you will see

```ruby
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
```

Simply stated it means that if the application happens to invoke id on a nil
object then throw an error. Rails assumes that under no circumstance a developer
wants to find id of a nil object. So this must be an error case and Rails throws
an exception.

The question I have is why 4. Why Matz chose the id of nil to be 4.
[This awesome presentation](http://confreaks.tv/videos/mwrc2008-ruby-internals)
on 'Ruby Internals' has the answer.

In short Matz decided to have all the odd numbers reserved for numerical values.
Check this out.

```ruby
> irb
>> 0.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 1
>> 1.id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 3
>> 2.id
(irb):3: warning: Object#id will be deprecated; use Object#object_id
=> 5
>> 3.id
(irb):4: warning: Object#id will be deprecated; use Object#object_id
=> 7
```

Id 1,3,5 and 7 are taken by 0,1,2 and 3.

Now we are left with the id 0,2,4 and higher values.

```ruby
> irb
> FALSE.id
(irb):5: warning: Object#id will be deprecated; use Object#object_id
=> 0
>> TRUE.id
(irb):6: warning: Object#id will be deprecated; use Object#object_id
=> 2
```

FALSE had the id 0 and TRUE has the id 2.

Now the next available id left is 4 and that is taken by NIL.

```ruby
> irb
>> NIL.id
(irb):7: warning: Object#id will be deprecated; use Object#object_id
=> 4
```

We won't even be discussing this issue once 1.9 comes out where we will have to
use `object_id` and then this won't be an issue.

You can follow more discussion about this article at
[Hacker news](https://news.ycombinator.com/item?id=3543695) .

## Links

- [Human page](https://www.bigbinary.com/blog/why-the-id-of-nil-is-4-in-ruby)
