Skip to content

Commit

Permalink
Fix Prime.include?
Browse files Browse the repository at this point in the history
Previously, it would be an infinite loop if passed a non-prime
integer.

Also, Prime.include? should also provide similar results to
Module#include? if passed a Module, so handle that.

For consistency with Enumerable#include?, return false if passed
other object types.

Fixes Ruby Bug 10167.
  • Loading branch information
jeremyevans committed Nov 20, 2019
1 parent 96638a6 commit 55dda6a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/prime.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,18 @@ def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
generator.each(&block)
end

# Return true if +obj+ is an Integer an is prime. Also returns
# true if +obj+ is a Module that is an ancestor of +Prime+.
def include?(obj)
case obj
when Integer
prime?(obj)
when Module
Module.instance_method(:include?).bind(Prime).call(obj)
else
false
end
end

# Returns true if +value+ is a prime number, else returns false.
#
Expand Down
8 changes: 8 additions & 0 deletions test/test_prime.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ def test_each
assert_equal PRIMES, primes
end

def test_include?
assert_equal(false, Prime.include?(nil))
assert_equal(true, Prime.include?(3))
assert_equal(false, Prime.include?(4))
assert_equal(true, Prime.include?(Enumerable))
assert_equal(false, Prime.include?(Comparable))
end

def test_integer_each_prime
primes = []
Integer.each_prime(1000) do |p|
Expand Down

0 comments on commit 55dda6a

Please sign in to comment.