True, False, and Nil In Ruby
Ruby is an open-sourced object-oriented programming language developed by Yukihiro Matsumoto. In Ruby, everything is treated as an object. true, false and nil are built-in data types of Ruby.
Note: Always remember in Ruby true, false, and nil are objects, not numbers. Whenever Ruby requires a Boolean value, then nil behaves like false and values other than nil or false behave like true.
True and False
In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass.
Note: Ruby does not contain Boolean class.
Let’s see a few examples of true and false in Ruby.
Example 1:
Ruby
a = 4
b = 4
if a == b
puts "True! a and b are equal"
else
puts "False! a and b are not equal"
end
|
Output:
True! a and b are equal
Example 2:
Ruby
a1 = "GeeksforGeeks"
b1 = "GeeksforGeeks"
result1 = a1 == b1
puts result1
a2 = "GeeksforGeeks"
b2 = "geeks"
result2 = a2 == b2
puts result2
|
Output:
true
false
Example 3:
Ruby
if 55 == 55
puts "GeeksforGeeks !"
else
puts " A Computer Science Portal for Geeks!"
end
|
Output:
GeeksforGeeks !
Nil
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby’s way of referring to nothing or void. Ruby also provide a nil? method to detect if any object is nil or not.
Example 1:
Output:
NilClass
Example 2:
Ruby
array = [ 1 , 2 , 3 , 4 , 5 ]
result1 = array[ 5 ]. nil ?
puts result1
result2 = array[ 2 ]. nil ?
puts result2
|
Output:
true
false
Last Updated :
02 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...