25

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.

1
  • How are you building the array in the first place to have either integers or empty strings? Seems like a strange combination to me... Commented Oct 17, 2013 at 15:21

9 Answers 9

55

To reject only nil would be:

array.compact

Sign up to request clarification or add additional context in comments.

Comments

21

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.

Comments

18

It is as simple as:

scores.grep(Integer)

Note that if you plan to map the values, you can do that in a block after:

scores.grep(Integer){|x| x+1 }

Bonus if you want to do the same thing, but your numbers are strings:

scores.grep(/\d+/){|x|x.to_i}

4 Comments

Grep is using the case equality operator (===), and I think that call is_a?
More info on the case-equality and classes here: ruby.about.com/od/beginningruby/qt/On-Case-And-Class.htm
You should use Integer, not Fixnum
Correct, changed original post.
2

Try this :

scores.select{|e| e.is_a? Integer}
# => [1, 2, 3, 4]

Comments

2

If you really need reject nil only, so it can be done like this:

scores.reject(&:nil?)

1 Comment

this is equivalent to scores.compact
1
scores = [1, 2, 3, "", 4, nil]
scores.reject{|s| s.to_s == ''}
# => [1, 2, 3, 4]

Comments

1

This Worked for me

scores.reject!{|x| x.to_s.empty?}

1 Comment

don't use bang method, if you really need it.
0
scores.select{|score| score.is_a? Fixnum}

or, as Fixnum inherits from Integer, you can also go for

scores.select{|score| score.is_a? Integer)

...if that seems more descriptive.

Array and Enumerable tend to offer many ways of doing the same thing.

Comments

0

&:empty? will work for hashes, arrays, and strings, but not numbers. The method you use in reject must be valid for all items in a list. &:blank? will work fine for this reason.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.