Search code examples
rubyprimes

Why this % Error in Ruby ? Beginner Learning


I just began with Ruby yesterday. I saw some basics online and started to do some beginner coding challenges and one asks for finding prime numbers. I try not using the prime feature already in Ruby. I think I almost have it, but I don't understand why the error shows itself.

"18:in ': undefined method %' for nil:NilClass (NoMethodError)"

I tried to tweak around it for a few hours now, and can't seem to find solutions to this online... I use Ruby 3.0.0, here's the code I managed to build until now:

nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
prime_nums = []
i = 0

#Loop on the array to check each element
while i <= nums.length
  check = 0
  divider = nums[i]

  #While to prevent DivisionByZero error
  while divider != 0
    if nums[i] % divider == 0    #/!\ ERROR HERE
      check += 1
    end
    divider -= 1
  end
  #Only division by 1 and itself will increment $check
  if check == 2
    prime_nums.append(nums[i])
  end
  i += 1
end
puts prime_nums

Solution

  • In your example it means that nums[i] returns nil, so the case is that i is greater than 19.

    You can change while i <= nums.length to while i < nums.length because arrays are indexed from 0 in Ruby.