2

c = [1,2,3,4,5,6,7,nil,nil,nil] c.map{ |i| p i if i > 10 }

NoMethodError: undefined method `>' for nil:NilClass

How to avoid 'nil' values during comparison?

3
  • You cant do > on nil in ruby Commented Mar 13, 2014 at 11:07
  • if there is any solution do avoid that? Commented Mar 13, 2014 at 11:09
  • nil.to_i will convert it to 0 Commented Mar 13, 2014 at 11:12

2 Answers 2

2

You can use compact to remove the nil values before applying map to it:

c.compact.map { |i| p i if i > 10 }
Sign up to request clarification or add additional context in comments.

Comments

2

Do this:

c.map { |i| p i if i.to_i > 10 }

The error is telling you that you can't compare nil. Telling ruby to explicitly convert i to an integer will convert nil values to 0.

> 0.to_i
 => 0
> 1.to_i
 => 1
> nil.to_i
 => 0

Note that here none of the values in your array validate the condition i > 10. Therefor it will return an array of nil values.

> c = [1,2,3,4,5,6,7,nil,nil,nil]
 => [1, 2, 3, 4, 5, 6, 7, nil, nil, nil]
> c.map { |i| i if i.to_i > 10 }
 => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

> c = [1,2,3,4,5,6,7,11,nil,nil]
 => [1, 2, 3, 4, 5, 6, 7, 11, nil, nil]
> c.map { |i| i if i.to_i > 10 }
 => [nil, nil, nil, nil, nil, nil, nil, 11, nil, nil]

You can use the compact method to clean the result:

> _.compact
 => [11]

Event better using select:

> c.select { |i| i.to_i > 10 }
 => [11]

4 Comments

It returns the nil for all values.
That's because none of the values in your array validate the condition i > 10
if c = ['2014-03-01 12-00-45 ","2014-03-17 22-05-07",nil,nil]
Those are dates not integers, different story.

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.