[前][次][番号順一覧][スレッド一覧]

ruby-changes:60305

From: Jeremy <ko1@a...>
Date: Fri, 6 Mar 2020 20:55:45 +0900 (JST)
Subject: [ruby-changes:60305] e79fc05a4c (master): [ruby/prime] Fix Prime.include?

https://git.ruby-lang.org/ruby.git/commit/?id=e79fc05a4c

From e79fc05a4ca672816c6b737d00a85fea4aa6c2b7 Mon Sep 17 00:00:00 2001
From: Jeremy Evans <code@j...>
Date: Sun, 11 Aug 2019 13:14:38 -0700
Subject: [ruby/prime] 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.

https://github.com/ruby/prime/commit/55dda6aa7f

diff --git a/lib/prime.rb b/lib/prime.rb
index 5be12f2..44129d2 100644
--- a/lib/prime.rb
+++ b/lib/prime.rb
@@ -141,6 +141,18 @@ class Prime https://github.com/ruby/ruby/blob/trunk/lib/prime.rb#L141
     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.
   #
diff --git a/test/test_prime.rb b/test/test_prime.rb
index 9db13f0..b809d15 100644
--- a/test/test_prime.rb
+++ b/test/test_prime.rb
@@ -27,6 +27,14 @@ class TestPrime < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/test_prime.rb#L27
     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|
-- 
cgit v0.10.2


--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]