Nice work - Why .instance / require 'prime' / Prime?


#1

3 questions:
-Why do we have to use .instance on Prime?
-Why the code starts whit "require 'prime'"?
-Why do we have to create an array equal to Prime, if such an array already exists?


#2

What exercise are you referring to pikkiuz?
Please attach a link and I will try my best to help you understand.

Regards,
Barry Allen


#3
require 'prime'

def first_n_primes(n)
  # Check for correct input!
  "n must be an integer" unless n.is_a? Integer
  "n must be greater than 0" if n <= 0

  # The Ruby 1.9 Prime class makes the array automatically!
  prime = Prime.instance
  prime.first n
end

first_n_primes(10)

#4

Hello @pikkiuz,

  1. We need to call Instance on prime because that is the method that generates a new Prime number...

  2. The code needs to start with "require Prime" because Prime is a module that contains the Prime Arrays and other functions and objects relating to primes.

  3. Codecademy has built this exercise primarily for introducing "Rubyistic" concepts such as one line conditionals and replacements for the for loop (the .times operator). The point of this exercise isn't to make a Prime Array function.

Hope you understand now...