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?
Try as below :
c.each { |i| p i if i.to_i > 10 } # fix is to use `to_i`
Use each method instead of map, when you want to traverse the array, and outputs some elements when there is a match, as you are doing. If you use the method to_i, then whenever there is nil in your source array, then nil.to_i will convert it to 0. And if it found any integers like 1,2 etc, then you will get back the same integers.
Look also NilClass#to_i and Fixnum#to_i methods.
There are a couple ways.
Use Array.compact:
c.compact.each { |i| p i if i > 10 }
The Array#compact method gives you a new array with all nils removed.
Use next:
c.each do |i|
next if i.nil?
p i if i > 10
end
This avoids creating a new array.
Note the use of each instead of map. The latter is used when you are creating a new array with the result of applying the block to each element in the original array, such as c.map { |i| i + 1 }, which is equivalent to c.map &:succ.
If all you need to do is iterate over the array and apply side effects such as printing numbers, each should suffice.
c.each { |i| p i if !i.nil? && i > 10 }
c.each { |i| p i if i && i > 10 } may be preferable to the double-negative (Unlike !i.nil?, this precludes false, which may not be a bad thing, as false would raise an exception.) c.each { |i| p i unless i.nil? || i <= 10 } is another way to express what you have.
p?