0
0
Rubyprogramming~5 mins

Nil as the absence of value in Ruby

Choose your learning style9 modes available
Introduction

Nil means there is no value or nothing there. It helps us show when something is empty or missing.

When you want to say a variable has no value yet.
When a method does not return anything meaningful.
When you want to check if something is missing or empty.
When you want to reset a variable to have no value.
Syntax
Ruby
variable = nil

Use nil to represent 'no value' in Ruby.

It is different from false or 0, which are actual values.

Examples
This sets name to nil and prints nothing (just a blank line).
Ruby
name = nil
puts name
First age has 25, then it is set to nil, so printing shows nothing.
Ruby
age = 25
age = nil
puts age
This method returns nil to show no user was found.
Ruby
def find_user(id)
  # no user found
  nil
end

puts find_user(10)
Sample Program

This program checks if user_name has no value (nil). If it is nil, it prints a message saying no name was given.

Ruby
user_name = nil
if user_name.nil?
  puts "No user name given"
else
  puts "User name is #{user_name}"
end
OutputSuccess
Important Notes

Use .nil? method to check if a variable is nil.

Nil is a special object in Ruby representing 'nothing'.

Summary

Nil means no value or absence of value.

Use nil to show something is empty or missing.

Check for nil with .nil? method.