What is .empty?() in Ruby?
Introduction
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.
Example
#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?
Explanation
- Line 2: We check if an array that contains numbers from 1 to 5 is empty or not. The output result is
false, as the array contains multiple values. - Line 4 : We check a selection of
x > 10elements for emptiness from a list that contains numbers from 1 to 10. The output istruebecause all of our values are less than 10. - Lines 6–7: We declare a null set and check for emptiness. It returns
truebecause no values are added to the set. - Line 9 : We check a string
"educative"for null values using the empty function. It returnsfalsebecause the string is not empty.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved