From: "LukeH7789 (Luke Hill) via ruby-core" Date: 2026-08-31T11:06:25+00:00 Subject: [ruby-core:126550] [Ruby Feature#22281] Feature: Permit `#with_index` to be used with `Integer#times` in a "simpler" format Issue #22281 has been updated by LukeH7789 (Luke Hill). Subject changed from Feature: Permit `#with_index` to be used with `#times` in a "simpler" format to Feature: Permit `#with_index` to be used with `Integer#times` in a "simpler" format Changed title to include Integer class ref ---------------------------------------- Feature #22281: Feature: Permit `#with_index` to be used with `Integer#times` in a "simpler" format https://bugs.ruby-lang.org/issues/22281#change-118743 * Author: LukeH7789 (Luke Hill) * Status: Open ---------------------------------------- ## 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` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/