3 ms·
There are other details that are wrong. Ruby does have iterators — except they're called enumerators. The standard implementation is called Enumerator: >>
by atombender 5y ago
There are other details that are wrong. Ruby does have iterators — except they're called enumerators. The standard implementation is called Enumerator:
>> [1, 2, 3].each
=> #<Enumerator: [1, 2, 3]:each>
>> e = [1, 2, 3].each
=> #<Enumerator: [1, 2, 3]:each>
>> e.next
=> 1
>> e.next
=> 2
>> e.next
=> 3
>> e.next
Traceback (most recent call last):
2: from (irb):17
1: from (irb):17:in `next'
StopIteration (iteration reached an end)
Enumerators behave similarly to generators in Python thanks to utilities like #to_enum:
class X
def each
yield 1
yield 2
yield 3
end
end
>> x = X.new.to_enum
>> x.each
#<Enumerator: #<X:0x00007fd30c93dfa0>:each>
>> x.next
1
[etc.]
Ruby's for loops actually use enumerators, just like Python. It's just not used as much, for cultural reasons; most devs these days favour Ruby's data-oriented inversion of control.