How to use Reject In Ruby
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.
# 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"]
How to Remove Empty String from Array in Ruby?
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.
Table of Content
- Remove empty string from array using reject
- Remove empty string from array using select
- Remove empty string from array using map and compact
Contact Us