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 and delete_if method to remove nil and blank string in an array in Ruby
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
:NOTE:
reject
with and without bang behaves the same way ascompact
with and without bang:reject!
andcompact!
modify the array itself whilereject
andcompact
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 onnil
, so the method call becomes:I would probably add
.strip
to eliminate potential whitespace headaches (assuming its not a rails app).try this out:
Hope this will work for your case :
You could do this:
Note
nil.to_s => ''
.