Skip to main content

Command Palette

Search for a command to run...

Booleans and nil in Ruby on Rails

Updated
•2 min read•View as Markdown
S

I am a Ruby on Rails developer from Nepal.

Today, we will learn about boolean and nil values in Ruby on Rails. Lets start with what these are.

What is a boolean?

A boolean value is used to represent whether the condition or the logic is true or false. In Ruby, we have boolean objects as "true" and "false".

str1 = "Hello"
str2 = "Hello"
result1 = str1 ==str2

puts result1

int1 = 5
int2 = 3
result2 = int1 == int2

puts result2

Output:

true
false

What is nil?

A "nil" is used to indicate "no value" or "unknown." In Ruby, nil is an object of Nilclass.

# Checking for Nil
array = [ 1, 2, 3]

# Here, array[4] does not exist so, it is nil.
result1 = array[4].nil?
puts result1

# here, array[2] exists so, it is not nil.
result2 = array[2].nil?
puts result2

Output:

true
false

In Ruby, only nil and false are false and everything else is true. Lets take an example:

if subscription
 puts "We have subscribed"
end

Here, Ruby checks if the subscription is true or false/nil before printing the string.

In some cases, if we have to call the method on an object like this:

if subscription.date
 puts "Subscribed date"
end

This may lead us to error it the paid is nil, to avoid error we can use the safe navigator like this.

if subscription&.date
 puts "Subscribed date"
end

Booleans Methods

Any methods ending with question marks are the boolean methods. They return either true or false. Some examples of Boolean methods are:

def empty? 
  ............
end

def paid?
  ....................
end

Hope have learned something about boolean in Ruby today. Thank you for reading. Happy Reading !! Keep Learning. :)