Project

General

Profile

Actions

Feature #11007

closed

Prime.each.with_index should accept offset

Added by ciel (T Yamada) about 9 years ago. Updated almost 9 years ago.

Status:
Closed
Target version:
-
[ruby-core:<unknown>]

Description

I'd like to execute following code:

Prime.each(10).with_index(1){|e,i|
  print i,' ',e,"\n"
}

Expected output:

1 2
2 3
3 5
4 7

I have attached a patch.


Files

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
Actions #1

Updated by marcandre (Marc-Andre Lafortune) about 9 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.

Actions #2

Updated by ciel (T Yamada) about 9 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...
Actions #3

Updated by nobu (Nobuyoshi Nakada) about 9 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
      end
    end

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

Actions #4

Updated by ciel (T Yamada) about 9 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) almost 9 years ago

Hi, any progress about this patch?

The reason why I have proposed this is that I'm anxious about the phrase of http://ruby-doc.org/stdlib-2.2.2/libdoc/prime/rdoc/Prime.html#class-Prime-label-Generators : "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) almost 9 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) almost 9 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0