0
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?

4
  • 1
    what's the expected output?? what's p? Commented Mar 14, 2014 at 11:02
  • seems he/she wants to output integers > 10 Commented Mar 14, 2014 at 11:03
  • 1
    @KarolyHorvath p() is a Kernel method that writes obj.inspect to the standard output. Commented Mar 14, 2014 at 11:05
  • @SaidKaldybaev: yes, of course... sry!! Commented Mar 14, 2014 at 11:06

4 Answers 4

3

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.

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

1 Comment

Using each is correct suggestion here. I would say to use array.compact to avoid undefined method error for comparison operator when used for nil in place of using nil.to_i
3

There are a couple ways.

  1. 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.

  2. 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.

Comments

1

Try this one:

c = [1, 2, 3, 4, 5, 6, 7, nil, nil, nil]

c.compact.each{|i| p i if i > 10}

Comments

1
c.each { |i| p i if !i.nil? && i > 10 }

1 Comment

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.

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.