Feature #9140
closedAllow each_with_index to get start index
Description
Is it possible for array.each_with_index(1){|el, i| ... } to be equivalent to array.each.with_index(1){...}?
Sometimes the application-domain index starts with 1, not 0. Currently each_with_index doesn't accept any arguments, so it wouldn't be backward incompatible if the start index defaults to 0.
Updated by mame (Yusuke Endoh) over 11 years ago
Unfortunately, it is incompatible because "each_with_index" actually accepts arguments and passes them to "each".
$ ruby -rstringio -e 'StringIO.new("foo|bar|baz").each_with_index("|") {|s, i| p [s, i] }'
["foo|", 0]
["bar|", 1]
["baz", 2]
$ ruby -rstringio -e 'StringIO.new("foo|bar|baz").each("|").with_index(1) {|s, i| p [s, i] }'
["foo|", 1]
["bar|", 2]
["baz", 3]
When I made a proposal to make "with_index" accept an offset, matz determined to leave "each_with_index" as it is.
--
Yusuke Endoh mame@tsg.ne.jp
Updated by rosenfeld (Rodrigo Rosenfeld Rosas) over 11 years ago
This is interesting because I noticed the *args in the documentation but it wasn't documented what it means. So I tried it but in a different context (adapting from your example):
%w(foo bar baz).each_with_index("|") {|s, i| p [s, i] }
ArgumentError: wrong number of arguments (1 for 0)
from (irb):3:in each' from (irb):3:in
each_with_index'
from (irb):3
from /home/rodrigo/.rvm/rubies/ruby-2.0.0-p353/bin/irb:12:in `'
That's why I assumed it didn't accept any arguments.
Updated by rosenfeld (Rodrigo Rosenfeld Rosas) over 11 years ago
Actually, it explains but I missed an example :) I do example driven development ;)
Updated by rosenfeld (Rodrigo Rosenfeld Rosas) over 11 years ago
By the way, feel free to reject this ticket then. I only created it because I thought it would be backwards compatible.
Updated by zzak (zzak _) over 11 years ago
So is this a doc bug?
On Nov 23, 2013, at 12:05 AM, "rosenfeld (Rodrigo Rosenfeld Rosas)" rr.rosas@gmail.com wrote:
Issue #9140 has been updated by rosenfeld (Rodrigo Rosenfeld Rosas).
By the way, feel free to reject this ticket then. I only created it because I thought it would be backwards compatible.¶
Feature #9140: Allow each_with_index to get start index
https://bugs.ruby-lang.org/issues/9140#change-43087Author: rosenfeld (Rodrigo Rosenfeld Rosas)
Status: Open
Priority: Normal
Assignee: matz (Yukihiro Matsumoto)
Category: lib
Target version:Is it possible for array.each_with_index(1){|el, i| ... } to be equivalent to array.each.with_index(1){...}?
Sometimes the application-domain index starts with 1, not 0. Currently each_with_index doesn't accept any arguments, so it wouldn't be backward incompatible if the start index defaults to 0.
Updated by rosenfeld (Rodrigo Rosenfeld Rosas) over 11 years ago
There's no bug. Just reject this feature request.
Updated by kosaki (Motohiro KOSAKI) over 11 years ago
- Status changed from Open to Rejected