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