Search code examples
rubyrecursionprime-factoring

Ruby: Getting an error when I use recursion to find prime numbers


So I've been trying to create a method that would display an array of prime numbers for any Integer that you insert as an argument, but I've been getting the weirdest error. Can anyone explain what this error means and how to solve my problem w/o using any gems? I've tried looking on Stack Overflow and haven't found a solution. Thanks!

def prime_factors(num, output = [])
  factor = (2..num-1).find(0){|divisor| num % divisor == 0} #returns nil if find fails.
  output << factor if factor != 0
  prime_factors(num/factor, output)
end

prime_factors(5)

The error I've been receiving is:

`find': undefined method `call' for 0:Fixnum (NoMethodError)
in `prime_factors'
in `<main>'

Solution

  • See the docs for Enumerable#find (which you call in the first line of your function: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find

    The parameter of find is called if no object of the Enumerable ((2..num-1) in your case) matches (that is, the given block always returned false). So find tries to find a Number for which num % divisor is equal to 0, but doesn't find one. Then, it calls the function supplied as parameter. You pass 0 for that parameter. So it tries to invoke 0 as a function (which is done by executing the call Method: 0.call). But 0 of class Fixnum has no such method (it is not a function but a number). That generates the error message.