Feature #11007

Prime.each.with_index should accept offset

Added by ciel (T Yamada) almost 5 years ago. Updated over 4 years ago.

Target version:


I'd like to execute following code:

  print i,' ',e,"\n"

Expected output:

1 2
2 3
3 5
4 7

I have attached a patch.


prime.diff (1.09 KB) prime.diff ciel (T Yamada), 03/27/2015 03:10 PM
prime_2.diff (1.2 KB) prime_2.diff ciel (T Yamada), 03/30/2015 07:39 AM

Updated by marcandre (Marc-Andre Lafortune) almost 5 years ago

  • Assignee set to marcandre (Marc-Andre Lafortune)

Looks good, thanks for this.

Only thing is that it would be best to avoid capturing the block (with &blk) if it's not required, for performance reason.

You're welcome to tweak your patch, or I can do it if you like.


Updated by ciel (T Yamada) almost 5 years ago

Umm, I don't know how to pass block to each_with_index safely (without capturing).
Of course I can remove calling each_with_index, but...

  • Note: I have updated email address, which I'd like for ChangeLog...

Updated by nobu (Nobuyoshi Nakada) almost 5 years ago

Kernel#proc captures the block given to the caller.

    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

and enum = Prime.each is needed before loop again.
It's better to split the test.


Updated by ciel (T Yamada) almost 5 years ago

Updated the diff.
Thank you for the advice.

By the way, is PseudoPrimeGenerator#with_object covered by the tests? I don't see test_enumerator_with_object stuff.
Perhaps, for example, we can count the number of primes by modulo 4?

Updated by ciel (T Yamada) over 4 years ago

Hi, any progress about this patch?

The reason why I have proposed this is that I'm anxious about the phrase of : "Furthermore, it is an external iterator of prime enumeration which is compatible with an Enumerator."
"Compatible Enumerator" should accept with_index(offset)...

Updated by marcandre (Marc-Andre Lafortune) over 4 years ago

Committed, thank you very much for the patch.

Found a small bug, btw, it's important to pass arguments to enum_for. Maybe you started from with_object that had the same problem (even worse there, since that argument is mandatory!). Also, enumerators should provide a way to calculate size lazily when possible (GH#931).

All good now :-)

Updated by marcandre (Marc-Andre Lafortune) over 4 years ago

  • Status changed from Open to Closed

Also available in: Atom PDF