Feature #11007
closedPrime.each.with_index should accept offset
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
Updated by marcandre (Marc-Andre Lafortune) about 10 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) about 10 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) about 10 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.
Updated by ciel (T Yamada) about 10 years ago
- File prime_2.diff prime_2.diff added
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 10 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 10 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 10 years ago
- Status changed from Open to Closed