Ruby is a dynamic programing language with many built-in libraries and functions to increase productivity. While working with programming languages such as Ruby, it's important to handle missing data or null values. Ruby offers multiple keywords for checking such data, for example: blank
, nil
, present
, and empty
. In this Answer, we'll cover the different uses of the empty
keyword.
The empty
function provides Ruby the functionality to check null values in different forms of collections like arrays, lists, sets, and so on. It can also be used for strings because they are also a collection of chars.
#Checking an array for null values.puts [1..5].empty?#Checking a list for null values based on a condition.puts (1..10).select{|x|x>10}.empty?#Checking a set for null values.s1 = Set[]puts s1.empty?()#Checking a string for null values.puts "educative".empty?
false
, as the array contains multiple values.x > 10
elements for emptiness from a list that contains numbers from 1 to 10. The output is true
because all of our values are less than 10.true
because no values are added to the set."educative"
for null values using the empty function. It returns false
because the string is not empty.Free Resources