How to use Map and Compact In Ruby
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.
# 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"]
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