Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby remove nil values from array with .reject

Tags:

I have an array:

scores = [1, 2, 3, "", 4] 

And I want to remove all blank values. But when I run this:

puts scores.reject(&:empty?) 

I get an error:

undefined method `empty' for 1:Fixnum 

How can I remove values that are not integers from my array in a one step process? I am using Ruby 1.9.3.

like image 997
Luigi Avatar asked Oct 17 '13 15:10

Luigi


People also ask

How do you remove null values from an array in Ruby?

When you want to remove nil elements from a Ruby array, you can use two methods: compact or compact! . They both remove nil elements, but compact! removes them permanently. In this shot, we will be talking about the compact!

How do you remove nil from an array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.


2 Answers

To reject only nil would be:

array.compact

like image 172
Bibiana Cristofol Amat Avatar answered Oct 09 '22 08:10

Bibiana Cristofol Amat


If you want to remove blank values, you should use blank?: (requires Rails / ActiveSupport)

scores.reject(&:blank?) #=> [1, 2, 3, 4] 

"", " ", false, nil, [], and {} are blank.

like image 39
Stefan Avatar answered Oct 09 '22 08:10

Stefan