1 / 4 - Error: private methodnew’ called for Prime:Class (NoMethodError)

I wasn’t getting any errors or results trying to run the refactored code in the browser so I went local on my Mac and was seeing an error:

first_n_primes.rb:8:in `first_n_primes': private method `new' called for Prime:Class (NoMethodError)
	from first_n_primes.rb:13:in `<main>'

I eventually came across this article, but it is closed: Prime.new and Prime.next obsolete in Ruby >2.2

Anyway, there was a Stack Overflow link there which lead me to the solution and the correct usage of the prime module, if you’re running it locally and using a version newer than 1.9 (I’m on 2.3.3p222). If you’re also trying to run code locally and on a version newer than 1.9 change the following lines:

prime = Prime.new


prime = Prime::EratosthenesGenerator.new

Will have to dig around some to find the old posts on this topic. The prime module changed after 1.9, I believe, and the above can be done very simply now…

require 'prime'

def first_n_primes(n)  
  return "n must be an integer." unless n.is_a? Integer
  return "n must be greater than 0." unless n > 0
  Prime.first n

puts first_n_primes(10)

But that is moot. We cannot leave this topic listed since posting of solutions is frowned upon. Comparative analysis that others can discuss is not, though. Perhaps explain a bit further, or keep up your research and report differences that crop up with each new iteration of Ruby.

I updated my original post to remove the entire code and just provide the one line that has to be updated based on your feedback. Thanks by the way!

1 Like

You’re welcome. I’m still unable to find the post where I had links and explanation for the brevity of that code. Will keep digging, since by my recall it gave some why’s and what-for’s. Wish my recall was so good I could give them now.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.