I am new to Ruby and stuck with this issue. Let's say I have an array like this:
arr = [1, 2, 's', nil, '', 'd']
and I want to remove nil and blank string from it, i.e. final array should be:
arr = [1, 2, 's', 'd']
I tried compact
but it gives this:
arr.compact!
arr #=> [1, 2, 's', '', 'd'] doesn't remove empty string.
I was wondering if there's a smart way of doing this in Ruby.
You can use compact with reject
or
The simplest and fast way of doing this is :
Note: I am considering the array might have string with white spaces in it.
You can do:
or:
or if you want to update
arr
object itself then:arr.reject(&:blank?)
Just use this, no need to anything else.
I tend to do:
returns:
You can also use
-
to remove allnil
and''
elements:Demonstration
Or
compact
andreject
with shortcut (in case you are not using Rails where you can just usearr.reject(&:blank?)
):Demonstration