In Ruby, you can remove all empty strings (""
) and return a new array by using the Array#reject
method, for example, like so:
strings = ["", "foo", "", "bar", "baz", ""] without_empty_strings = strings.reject { | str | str.empty? } print without_empty_strings #=> ["foo", "bar", "baz"] print strings #=> ["", "foo", "", "bar", "baz", ""]
As you can see in the example above, this will return a new array with all the values from the original array, except empty strings (if any).
If you want to mutate the original array instead, then you can simply use Array#reject!
(instead of Array#reject
). For example:
strings = ["", "foo", "", "bar", "baz", ""] strings.reject! { | str | str.empty? } print strings #=> ["foo", "bar", "baz"]
You can also shorten either of these, by using the &:
syntax. For example, you can shorten the code using the Array#reject
method in the following way:
strings = ["", "foo", "", "bar", "baz", ""] without_empty_strings = strings.reject(&:empty?) print without_empty_strings #=> ["foo", "bar", "baz"] print strings #=> ["", "foo", "", "bar", "baz", ""]
This will return a new array with all the empty strings removed. Similarly, you can shorten the Array#reject!
method like so:
strings = ["", "foo", "", "bar", "baz", ""] strings.reject!(&:empty?) print strings #=> ["foo", "bar", "baz"]
This will mutate the original array, removing all empty strings from it.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.