简体   繁体   中英

Undefined method `%' for nil:NilClass (NoMethodError) Ruby on Rails

Getting an undefined method error for '%' for nil:NilClass (NoMethodError)

Here's the simple function I have:

def oddball_sum(numbers)
  i =0
  arr = []

  while i <= numbers.length
     if numbers[i] % 2 != 0
     arr << numbers[i]
     end
     i +=1
  end
   return arr.sum
end

Can't determine the issue; the method is supposed to take an array of integers and return the sum of all the odd elements.

Suppose that numbers is [1,2,3,4], when i increase to 4, numbers[4] will return nil

The condition should be i < numbers.length

Instead of using while , you can also use inject

numbers.inject(0) { |sum, i| i % 2?= 0: sum + i : sum }

You can go through arrays on the ruby docs ruby is one of the elegantly written languages. less code to achieve the same result. As follow the solution this would do

numbers.select {|num| num.odd? }.sum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM