← Back to Blog

Investigating Ruby's nil: Is it null?

Published: July 8, 2025
Tags: ruby, null

Introduction

When encountering nil in Ruby, I've always wondered "Is this actually null?" This article dives deep into understanding what Ruby's nil really is.

System Specifications

MacBook Air M2 arm64

Background Knowledge

Null

Null means "pointing to nothing." Accessing a null reference results in a null pointer access. Think of it as representing nothingness or void.

Pointers

A pointer refers to the memory address of variables, functions, or other data structures. For functions and arrays, it points to the starting address of the allocated memory region. Multi-dimensional arrays have more complex referencing patterns, but we'll skip that for now.

In the simplified diagram below, when we define int a = 1;, it's stored at memory address 0x0000_XXX1. When we define b as a pointer type and reference &a, b points to the memory address of a.

Pointer diagram

Null Pointers

Based on the pointer concept above, what happens when we reference null? Since null represents nothing, the computer doesn't know what to reference, leading to crashes or unexpected behavior.

Therefore, C languages perform null checks, and high-level languages implement NullPointerExceptions. Careful handling of null is essential.

Tagged Pointers

In Ruby, integers, boolean values (true/false), and nil are all objects. However, allocating memory every time these are used would make Ruby extremely slow.

Therefore, Ruby (especially CRuby) uses a technique where the lower few bits of pointer values are used as tags to distinguish the type of value. This is called tagged pointers.

Ruby VALUE Internal Structure

Ruby's Internal Value (VALUE) Structure:
64-bit data → Determine type by lower bits (tags)

Tag patterns:
...00  → Pointer: Address pointing to heap object
...01  → Fixnum: Integer value itself (not a pointer)
...100 (0x4) → nil: Special immediate value
...000 (0x0) → false: Special immediate value  
...010 (0x2) → true: Special immediate value

Key Insights

Ruby's nil vs C's NULL

Unlike C's NULL (which is typically 0x0), Ruby's nil is not actually null. It's a special immediate value with the tag pattern 0x4, representing a specific type within Ruby's object system.

Memory Safety

This tagged pointer system allows Ruby to:

Conclusion

Ruby's nil is not the same as null in lower-level languages. It's a carefully designed immediate value that maintains Ruby's "everything is an object" philosophy while providing memory safety and performance benefits. This tagged pointer approach is one of the clever implementation details that makes Ruby both safe and efficient.