Skip to content

Commit 55dda6a

Browse files
committed
Fix Prime.include?
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.
1 parent 96638a6 commit 55dda6a

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/prime.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,18 @@ def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
141141
generator.each(&block)
142142
end
143143

144+
# Return true if +obj+ is an Integer an is prime. Also returns
145+
# true if +obj+ is a Module that is an ancestor of +Prime+.
146+
def include?(obj)
147+
case obj
148+
when Integer
149+
prime?(obj)
150+
when Module
151+
Module.instance_method(:include?).bind(Prime).call(obj)
152+
else
153+
false
154+
end
155+
end
144156

145157
# Returns true if +value+ is a prime number, else returns false.
146158
#

test/test_prime.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ def test_each
2727
assert_equal PRIMES, primes
2828
end
2929

30+
def test_include?
31+
assert_equal(false, Prime.include?(nil))
32+
assert_equal(true, Prime.include?(3))
33+
assert_equal(false, Prime.include?(4))
34+
assert_equal(true, Prime.include?(Enumerable))
35+
assert_equal(false, Prime.include?(Comparable))
36+
end
37+
3038
def test_integer_each_prime
3139
primes = []
3240
Integer.each_prime(1000) do |p|

0 commit comments

Comments
 (0)