Issue #10498 has been updated by Robert Klemme.


I am actually against this feature.  Reason: an infinite loop does not need a counter.  We incur the cost of counting (especially when the figure leaves Fixnum space) on _all_ infinite loops.  For loops that have a fixed condition on the number (some have been shown with step take or other) that condition can be used upfront with a range or #step.

One can create a counting infinite loop like this:

~~~
x = Enumerator::Generator.new {|y| i = 0; loop {y << i; i += 1}}
~~~

or even

~~~
x = Enumerator::Generator.new {|y| i = -1; loop {y << (i += 1)}}
~~~

If needed that can be made a constant somewhere, e.g. in Enumerator.

----------------------------------------
Feature #10498: Make `loop` yield a counter
https://bugs.ruby-lang.org/issues/10498#change-49991

* Author: Franck Verrot
* Status: Open
* Priority: Normal
* Assignee: ruby-core
* Category: core
* Target version: current: 2.2.0
----------------------------------------
# Problem

Teaching Ruby, we always end up with that type of construct

```ruby
i = 0
loop do
  i += 1
  # do something with i....
  raise StopIteration if i ...
end
```

# Solution

What I propose with this patch is making `loop` yield the iteration count:

```ruby
loop do |i|
  # do something with i....
  raise StopIteration if i ...
end
```

`i` starts at 0 and stops at `FIXNUM_MAX` (there's no `Float::Infinity` equivalent for integers).

# Alternate solution

`Integer#times` could work if we had an `<Integer's infinity>` object, so we would just do `<Integer's Infinity>.times { |i| ... }`.

Also, this is the very first patch I submit to Ruby, I might have done something horrible, feel free to tell me :-)

---Files--------------------------------
0001-vm_eval.c-loop-now-yields-a-incremented-counter.patch (1.74 KB)
0001-vm_eval.c-loop-now-yields-a-incremented-counter.patch (1.86 KB)


-- 
https://bugs.ruby-lang.org/