summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog5
-rw-r--r--lib/prime.rb10
-rw-r--r--test/test_prime.rb11
3 files changed, 25 insertions, 1 deletions
diff --git a/ChangeLog b/ChangeLog
index 52b878c75a..4104d244cc 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+Sat Jun 13 00:44:59 2015 Marc-Andre Lafortune <ruby-core@marc-andre.ca>
+
+ * lib/prime.rb: Have with_index accept an offset parameter.
+ Based on patch by T Yamada. [#11007]
+
Fri Jun 12 22:21:12 2015 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
* test/ruby/test_extlibs.rb (TestExtLibs::check_existence): fix
diff --git a/lib/prime.rb b/lib/prime.rb
index d361e96720..757538db79 100644
--- a/lib/prime.rb
+++ b/lib/prime.rb
@@ -269,7 +269,15 @@ class Prime
end
# see +Enumerator+#with_index.
- alias with_index each_with_index
+ def with_index(offset = 0)
+ return enum_for(:with_index, offset) unless block_given?
+ return each_with_index(&proc) if offset == 0
+
+ each do |prime|
+ yield prime, offset
+ offset += 1
+ end
+ end
# see +Enumerator+#with_object.
def with_object(obj)
diff --git a/test/test_prime.rb b/test/test_prime.rb
index cdb6f8930e..5975336023 100644
--- a/test/test_prime.rb
+++ b/test/test_prime.rb
@@ -86,6 +86,17 @@ class TestPrime < Test::Unit::TestCase
end
end
+ def test_enumerator_with_index_with_offset
+ enum = Prime.each
+ last = 5-1
+ enum.with_index(5).each do |p,i|
+ break if i >= 100+5
+ assert_equal last+1, i
+ assert_equal PRIMES[i-5], p
+ last = i
+ end
+ end
+
def test_default_instance_does_not_have_compatibility_methods
assert !Prime.instance.respond_to?(:succ)
assert !Prime.instance.respond_to?(:next)