Project

General

Profile

Actions

Feature #22281

closed

Feature: Permit `#with_index` to be used with `Integer#times` in a "simpler" format

Feature #22281: Feature: Permit `#with_index` to be used with `Integer#times` in a "simpler" format

Added by LukeH7789 (Luke Hill) 21 days ago. Updated 21 days ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:126549]

Description

Synopsis

This is half a bug. Half a feature request (And my first), so bare with me.

When using Array#each_with_index or Array#each then chaining #with_index, it works as expected.

However when using Integer#times then chaining #with_index it ignores the supplied argument. I investigated this further and found that it's working "semi" as expected, but in a non-standard way when using times. Where we only have a single value being iterated. As such storing a secondary "new" index, alongside the previous "old" index, feels a bit redundant, possibly a waste of resources, and I would argue never valuable. Why would you ask for a new index, but yet rely on the old one??

Examples

4.0.5 :001 > 3.times do |i|
4.0.5 :002 >   p i
4.0.5 :003 > end
0
1
2

4.0.5 :004 > 3.times.with_index(5) do |i|
4.0.5 :005 >   p i
4.0.5 :006 > end
0
1
2

4.0.5 :007 > 3.times.to_a
 => [0, 1, 2] 
4.0.5 :008 > 3.times.with_index(5).to_a
 => [[0, 5], [1, 6], [2, 7]] 

The last example suggests that each of the #with_index calls is not mutating the index, but adding a second index value on. I investigated this further

4.0.5 :009 > %i(a b c)
 => [:a, :b, :c] 
4.0.5 :010 > %i(a b c).each_with_index.to_a
 => [[:a, 0], [:b, 1], [:c, 2]] 
4.0.5 :011 > %i(a b c).each.with_index.to_a
 => [[:a, 0], [:b, 1], [:c, 2]] 
4.0.5 :012 > %i(a b c).each.with_index(5).to_a
 => [[:a, 5], [:b, 6], [:c, 7]] 
4.0.5 :013 > 3.times.with_index(5) do |_unused_i, i|
4.0.5 :014 >   p i
4.0.5 :015 > end
5
6
7

Suggestion/Request/Solution

I therefore propose that when calling Integer#times and then chaining #with_index we mutate the iterating index in question (Same as we do when using Array#times and then chaining #with_index

Actions

Also available in: PDF Atom