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:40

You can use compact with reject

arr = [1, 2, 's', nil, '', 'd']
arr = [1, 2, 's', 'd']

arr = arr.compact.reject { |h| h == "" }

or

arr = arr.compact.delete_if { |h| h == "" }
查看更多
▲ chillily
3楼-- · 2020-02-26 14:41

The simplest and fast way of doing this is :

arr = [1, 2, 's', nil, '', 'd'] - [nil,'']
==> arr = [1, 2, 's', 'd']
查看更多
走好不送
4楼-- · 2020-02-26 14:43

Note: I am considering the array might have string with white spaces in it.

You can do:

arr = [1, 2, 's', nil, ' ', 'd']
arr.reject{|a| a.nil? || (a.to_s.gsub(' ', '') == '') }
#=> [1, 2, "s", "d"]

or:

arr.reject{|a| a.nil? || (a.to_s.gsub(' ', '').empty?) }
#=> [1, 2, "s", "d"]

or if you want to update arr object itself then:

arr.reject!{|a| a.nil? || (a.to_s.gsub(' ', '') == '') } # notice the ! mark, it'll update the object itself.
p arr #=> [1, 2, "s", "d"]
查看更多
放荡不羁爱自由
5楼-- · 2020-02-26 14:44

arr.reject(&:blank?)

Just use this, no need to anything else.

查看更多
看我几分像从前
6楼-- · 2020-02-26 14:49

I tend to do:

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

returns:

=> [1, 2, "s", "d"]
查看更多
The star\"
7楼-- · 2020-02-26 14:49

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

查看更多
登录 后发表回答