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?
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]
i > 10
>onnilin rubynil.to_iwill convert it to 0