Remove nil and blank string in an array in Ruby

2020-02-26 14:32发布

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.

标签: ruby arrays
12条回答
叛逆
2楼-- · 2020-02-26 14:50

You can use compact and delete_if method to remove nil and blank string in an array in Ruby

arr = [1, 2, 's', nil, '', 'd']
arr.compact!.delete_if{|arrVal| arrVal.class == String and arrVal.empty?}
=> [1, 2, "s", "d"]
查看更多
The star\"
3楼-- · 2020-02-26 14:52

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? }
查看更多
仙女界的扛把子
4楼-- · 2020-02-26 14:53

I would probably add .strip to eliminate potential whitespace headaches (assuming its not a rails app).

array = [1, 2, "s", nil, "     ", "d", "\n"]
array.reject!{|a| a.nil? || (a.to_s.strip.empty?) }

#=> [1, 2, "s", "d"]
查看更多
可以哭但决不认输i
5楼-- · 2020-02-26 14:56

try this out:

[1, 2, "s", nil, "", "d"].compact.select{|i| !i.to_s.empty?}
查看更多
女痞
6楼-- · 2020-02-26 14:57

Hope this will work for your case :

arr = [1, 2, 's', nil, '', 'd']
arr.select{|x| x.to_s!="" }
查看更多
forever°为你锁心
7楼-- · 2020-02-26 15:02

You could do this:

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

Note nil.to_s => ''.

查看更多
登录 后发表回答