diff --git a/lib/prime.rb b/lib/prime.rb index b2b55f1..aa0df07 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, &blk) + 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(&blk) 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..38d4fc4 100644 --- a/test/test_prime.rb +++ b/test/test_prime.rb @@ -90,6 +90,13 @@ class TestPrime < Test::Unit::TestCase assert_equal PRIMES[i], p last = i end + 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