Open In App

How to Remove Empty String from Array in Ruby?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to remove empty strings from an array in Ruby. We can remove empty strings from an array in Ruby using various methods.

Using Reject

The reject method creates a new array containing elements for which the block returns false or nil. In this case, we’ll use it to reject empty strings.

Syntax:

array.reject { |element| element.empty? }

Example:

In this example, we have an array of strings that includes some empty strings. We use reject to create a new array that excludes these empty strings.

Ruby
# Original array containing strings, 
# including empty strings
array = ["hello", "", "world", "", "ruby"]

# Removing empty strings from an array 
# using reject to remove empty strings
result = array.reject { |element| element.empty? }
puts result.inspect  

Output
["hello", "world", "ruby"]

Using Select

The select method returns a new array containing elements for which the block returns true. By using select with the condition element != "", we can remove empty string from array.

Syntax:

array.select { |element| element != “” }

Example: 

In this example, we use select to create a new array containing elements that are not empty strings.

Ruby
# Original array containing strings, 
# including empty strings
array = ["hello", "", "world", "", "ruby"]

#Removing empty strings using select 
# to remove empty strings
result = array.select { |element| element != "" }
puts  result.inspect  

Output
["hello", "world", "ruby"]

Using Map and Compact

The compact method removes nil elements from an array. To remove empty strings, we can first use map to convert empty strings to nil and then use compact

Syntax:

array.map { |element| element.empty? ? nil : element }.compact

Example:

In this example, we convert each empty string to nil using map, and then use compact to remove the nil values, effectively removing the empty strings.

Ruby
# Original array containing strings, 
# including empty strings
array = ["hello", "", "world", "", "ruby"]

# Removing empty strings using map and 
# compact to remove empty strings
result = array.map { |element| element.empty? ? nil : element }.compact
puts  result.inspect   

Output
["hello", "world", "ruby"]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads