Object#nil?
obj.nil? -> true or false The nil? method is defined on Object and returns true if the object is nil, and false otherwise. In Ruby, nil represents the absence of a value—the only member of the NilClass. Every other object returns false when nil? is called.
Syntax
object.nil?
Parameters
nil? takes no parameters.
Examples
Basic usage
nil.nil?
# => true
"hello".nil?
# => false
42.nil?
# => false
Checking for nil in conditionals
def find_user(id)
user = database.find_by(id: id)
if user.nil?
puts "User not found"
return nil
end
user
end
Common pattern: safe navigation with nil checks
# Before using a potentially nil value
name = params[:user]&.fetch(:name)
if name.nil?
name = "Anonymous"
end
Common Patterns
The nil check pattern
Ruby developers frequently check for nil before using values:
def greet(user)
return "Hello, stranger!" if user.nil?
"Hello, #{user.name}!"
end
Combining with logical operators
# Use || to provide a default value
name = nil_value || "default"
# Use && for conditional execution
result = value && process(value)
Hash.fetch with default
Instead of checking nil?, use Hash#fetch:
config = { timeout: 30 }
# Instead of:
timeout = config[:timeout]
timeout = 60 if timeout.nil?
# Use:
timeout = config.fetch(:timeout, 60)
Errors
Calling nil? never raises an error—it works on all objects.