how to remove nil and blank string in an array in Ruby

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 could do this:

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

Note nil.to_s => ''.

If arr might contain another kind of empty object (e.g, array or hash) that you wish to keep, change e.to_s.empty? to e.to_s == ''


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章