# The Difference Between nil?, empty?, and blank? in Ruby

*Published on October 07, 2023*

---


### nil?

As expected, you can use&nbsp;`nil?`&nbsp;to check if an object is nil. It returns&nbsp;`true`&nbsp;only when the object is&nbsp;`nil`. For all other values, it returns&nbsp;`false`.

```ruby
nil_object = nil
nil_object.nil?   # true

data = Hash.new
data.nil?         # false
```

### empty?

You can use this method on strings, arrays, and hashes. It returns&nbsp;`true`&nbsp;in the following cases:

1. String doesn’t have any characters, i.e.&nbsp;`str.length == 0`
2. Array doesn’t contain any elements, i.e.&nbsp;`arr.length == 0`
3. Hash doesn’t have any key-value pairs, i.e.&nbsp;`hash.length == 0`

```ruby
[].empty?         # true
''.empty?         # true
{}.empty?         # true
nil.empty?        # NoMethodError
false.empty?      # NoMethodError
```

It’s important to note that an object can be empty and not&nbsp;`nil`. For example:

```ruby
names = []
names.empty?  # true
names.nil?    # false
```

If you try to call&nbsp;`.empty?`&nbsp;on a&nbsp;`nil`&nbsp;or any other object, Ruby throws&nbsp;`NoMethodError`.

```ruby
nil.empty?

# undefined method `empty?' for nil:NilClass (NoMethodError)
```

### blank?

This is a nice syntactic sugar implemented in Rails. An object is blank if it’s&nbsp;`nil`,&nbsp;`false`, or&nbsp;`empty`. For example,&nbsp;`nil`,`false`,&nbsp;`''`,&nbsp;`[]`,&nbsp;`{}`are all blank.

You can think of&nbsp;`blank?`&nbsp;as a shorthand for the following code.

```ruby
!val || val.empty?
```

Here's how it works for various values.

```ruby
nil.blank?    # true
false.blank?  # true
''.blank?     # true
[].blank?     # true
{}.blank?     # true
```

In addition,&nbsp;`.blank?`&nbsp;returns true if a string contains only whitespace characters.

```ruby
"  ".blank? # true
```

Rails also provides&nbsp;`present?`, which is the opposite of&nbsp;`blank?`. It checks if the value is not&nbsp;`blank`.

