Feature #11007
closed
Prime.each.with_index should accept offset
Added by ciel (T Yamada) over 9 years ago.
Updated about 9 years ago.
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
- 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.
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...
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 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?
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 :-)
- Status changed from Open to Closed
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0