Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nil and blank string in an array in Ruby

Tags:

arrays

ruby

People also ask

How do you remove Blank strings from an array in Ruby?

Active Support is a library of “useful” things that support (!) the other parts of Rails. It includes ways to extend the base Ruby classes, such as Hash , String and Integer .

How do you remove nil from an array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

How do you get rid of nil in Ruby?

When you want to remove nil elements from a Ruby array, you can use two methods: compact or compact! . They both remove nil elements, but compact! removes them permanently. In this shot, we will be talking about the compact!

Is empty array nil in Ruby?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil. Neither is something that is false nil. => NilClassnil.


You could do this:

arr.reject { |e| e.to_s.empty? } #=> [1, 2, "s", "d"]

Note nil.to_s => ''.


Since you want to remove both nil and empty strings, it's not a duplicate of How do I remove blank elements from an array?

You want to use .reject:

arr = [1, 2, 's', nil, '', 'd']
arr.reject { |item| item.nil? || item == '' }

NOTE: reject with and without bang behaves the same way as compact with and without bang: reject! and compact! modify the array itself while reject and compact return a copy of the array and leave the original intact.

If you're using Rails, you can also use blank?. It was specifically designed to work on nil, so the method call becomes:

arr.reject { |item| item.blank? }

I tend to do:

arr = [1, 2, 's', nil, '', 'd']
arr.reject(&:blank?)

returns:

=> [1, 2, "s", "d"]

arr.reject(&:blank?)

Just use this, no need to anything else.


You can also use - to remove all nil and '' elements:

arr -= [nil, '']
#=> [1, 2, "s", "d"]

Demonstration

Or compact and reject with shortcut (in case you are not using Rails where you can just use arr.reject(&:blank?) ):

arr = arr.compact.reject(&''.method(:==))
#=> [1, 2, "s", "d"]

Demonstration


compact_blank (Rails 6.1+)

If you are using Rails (or a standalone ActiveSupport), starting from version 6.1, there is a compact_blank method which removes blank values from arrays.

It uses Object#blank? under the hood for determining if an item is blank.

[1, 2, 's', nil, '', 'd'].compact_blank
# => [1, 2, 's', 'd']

[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# => [1, 2, true]

Here is a link to the docs and a link to the relative PR.

A destructive variant is also available. See Array#compact_blank!.