Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.empty? in Ruby?

okwudili onyejiaku

.empty? is a method in Ruby that checks if an array is empty or not. .empty? returns a Boolean value true or false. The method returns true if the array is actually empty; otherwise, it returns false.

Syntax

array.empty?

Parameters

.empty? does not accept any parameters. It is only called on an array.

Return value

The .empty? method returns true if the array is empty; otherwise, it returns false.

Example

In the code below, we create arrays and call the empty? method on them. Then, we print the returned values to the console.

# creating arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Ruby on Rails!", "Java", "C++", "Python", "Javascript" ]
array4 = [nil, nil]
array5 = []
array6 = [false, true, 1, 0]

# check if arrays are empty
a = array1.empty?
b = array2.empty?
c = array3.empty?
d = array4.empty?
e = array5.empty?
f = array6.empty?

# print returned values to console
puts "#{array1} is empty? : #{a}"   # false
puts "#{array2} is empty? : #{b}"   # false
puts "#{array3} is empty? : #{c}"   # false
puts "#{array4} is empty? : #{d}"   # false
puts "#{array5} is empty? : #{e}"   # true
puts "#{array6} is empty? : #{f}"   # false

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring