Penny
Penny

Reputation: 1280

I have a hard time understanding some of the Ruby code

I'm having a hard time understanding the two lines of the code in codecademy.

require 'prime'

def first_n_primes(n)
  "n must be an integer" unless n.is_a? Integer
  "n must be greater than 0" if n <= 0
  prime = Prime.instance
  prime.first n
end

first_n_primes(10)

Can you please explain what Prime.instance means and what prime.first n is?

Upvotes: 1

Views: 87

Answers (2)

sawa
sawa

Reputation: 168249

Prime numbers are a universal notion, and you don't need to think about creating different instances of the enumerator/set of primes each time you use it your code. (Ideally,) it should be comparable to modules/methods on which you call singleton methods like:

Math.sin(0)

instead of the wrong form:

Math.new.sin(0)

However, Prime class was (incorrectly) designed to be used like in the latter form above:

Prime.new.each(30)

with there being only a single instance of the prime enumerator (i.e., Prime being a singleton class). So for historical reason, this usage is kept (up to Ruby 2.2), but it was later noticed that, since it is a singleton, it should be encouraged to replace new by instance:

Prime.instance.each(30)

as with classes that include the Singleton module do.

Regarding your first n, it takes the first n elements from the enumerator.

Upvotes: 7

Brian Mock
Brian Mock

Reputation: 41

Prime is a Ruby class. By calling prime = Prime.instance, you are instantiating an object called prime of the Prime class, which is basically the set of all prime numbers. This object has the public methods of the class Prime including #first which when presented an argument (n), will return an array of the first n prime numbers.

Upvotes: 3

Related Questions