From dd8f914d3ba6ffb256376e724b3e249facfdc888 Mon Sep 17 00:00:00 2001 From: marcandre Date: Fri, 12 Jun 2015 15:45:22 +0000 Subject: [PATCH] * lib/prime.rb: Have with_index accept an offset parameter. Based on patch by T Yamada. [#11007] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@50854 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ lib/prime.rb | 10 +++++++++- test/test_prime.rb | 11 +++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) 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 + + * 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 * 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)