Skip to content

Commit

Permalink
Prevent people from using Ruby's Prime class to implement the nth-pri…
Browse files Browse the repository at this point in the history
…me exercise

See: Issue #95
  • Loading branch information
Martin Tournoij authored and kytrinyx committed Mar 31, 2015
1 parent debd447 commit 0e55df1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
13 changes: 10 additions & 3 deletions nth-prime/example.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
require 'prime'

class Prime
def self.nth(n)
if n < 1
Expand All @@ -11,8 +9,17 @@ def self.nth(n)
i = 1
while primes < n
i += 1
primes += 1 if Prime.prime?(i)
primes += 1 if self.prime?(i)
end
i
end

def self.prime?(n)
return false if n == 1
return true if n == 2
(2..Math.sqrt(n).ceil).each do |i|
return false if n % i == 0
end
return true
end
end
17 changes: 17 additions & 0 deletions nth-prime/nth_prime_test.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
require 'minitest/autorun'

require 'prime'
Error_message = "Using Ruby's Prime class is probably the best way to do this in a 'real'\n" +
"application; but this is an exercise, not a real application, so you're\n" +
"expected to implement this yourself ;-)"
class Prime
[:each, :new, :prime?, :take].each do |m|
define_method(m) { |*_| raise Error_message }
end
end

class Integer
[:prime?, :each_prime].each do |m|
define_method(m) { |*_| raise Error_message }
end
end

require_relative 'nth_prime'

class TestPrimes < Minitest::Test
Expand Down

0 comments on commit 0e55df1

Please sign in to comment.