Codestudio
Codestudio

Reputation: 525

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.

Upvotes: 0

Views: 590

Answers (2)

okoth kongo
okoth kongo

Reputation: 71

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

Upvotes: 0

Thuy Nguyen
Thuy Nguyen

Reputation: 362

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 }

Upvotes: 2

Related Questions