How to Use the empty? Method in Ruby

09/20/2021

Contents

In this article, you will learn how to use the empty? method in Ruby.

The empty? Method

In Ruby, the empty? method is used to check whether a given object is empty or not. It can be used on many different types of objects, including strings, arrays, hashes, and more.

Here are some examples of how to use the empty? method in Ruby:

Strings
string = "Hello"
puts string.empty? # false

empty_string = ""
puts empty_string.empty? # true
Arrays
array = [1, 2, 3]
puts array.empty? # false

empty_array = []
puts empty_array.empty? # true
Hashes
hash = { key: "value" }
puts hash.empty? # false

empty_hash = {}
puts empty_hash.empty? # true

As you can see, the empty? method returns true if the object is empty, and false otherwise.

 

Here are some additional details about the empty? method in Ruby:

  • The empty? method can be used on any object that responds to the length method. This includes strings, arrays, hashes, and more.
  • The empty? method returns a boolean value (true or false) indicating whether the object is empty or not.
  • For strings, the empty? method returns true if the string has a length of zero (i.e., it is an empty string). For arrays and hashes, the empty? method returns true if the collection has no elements.
  • It’s important to note that the empty? method does not modify the object it is called on. It simply checks whether the object is empty or not.
  • The empty? method is often used in conditional statements to check whether a collection is empty or not. For example:

    # Check if an array is empty before iterating over its elements
    my_array = []
    if my_array.empty?
      puts "The array is empty"
    else
      my_array.each { |element| puts element }
    end
    
  • You can also chain the empty? method with other methods that return collections, such as map, select, and reject. For example:

    # Check if any elements in an array meet a condition
    my_array = [1, 2, 3, 4, 5]
    if my_array.select { |num| num.even? }.empty?
      puts "There are no even numbers in the array"
    else
      puts "There are even numbers in the array"
    end