Range Over Iterators in Ruby
Our example program demonstrates iteration over custom data structures and an infinite sequence generator. Here’s the full source code translated to Ruby.
Example
We start by defining the List
class, which uses a linked list structure to hold elements.
Pushing elements into the list
Method push
adds an element to the list, handling both the empty and non-empty cases.
Iterating over the list
We can iterate over the list
using Ruby’s Enumerator
.
Collecting all elements
Ruby has built-in methods like to_a
to collect values from an Enumerator
.
Infinite sequence generator
Next, we define a generator for Fibonacci numbers. The fib_gen
method yields Fibonacci numbers indefinitely.
Using the Fibonacci generator
We can iterate over our Fibonacci generator and break under conditions we define.
Output of running the code
In summary, we translated the example to Ruby, focusing on idiomatic use of classes, methods, and Ruby’s powerful enumerator-based iteration. This translation demonstrates handling of both finite and infinite sequences elegantly.