diff --git a/lib/prime.rb b/lib/prime.rb index b2b55f1..27fe193 100644 --- a/lib/prime.rb +++ b/lib/prime.rb @@ -289,7 +289,16 @@ class Prime end # see +Enumerator+#with_index. - alias with_index each_with_index + def with_index(offset = 0) + return enum_for(:with_index) unless block_given? + # if offset == 0, use each_with_index, which is faster because of C implementation. + 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 885406f..0cbe512 100644 --- a/test/test_prime.rb +++ b/test/test_prime.rb @@ -92,6 +92,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) 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)