Range Over Channels in Ruby
Our first example demonstrates how to iterate over values received from a channel. Here’s the full source code:
To run the program, save the code in a file (e.g., range_over_queue.rb
) and use the ruby
command:
In this Ruby example, we’re using the Queue
class from the standard library, which provides thread-safe queue operations. While it’s not an exact equivalent to Go’s channels, it serves a similar purpose for passing data between different parts of a program.
The until queue.empty?
loop continues to retrieve and print elements from the queue until it’s empty. This is analogous to ranging over a channel in Go.
It’s worth noting that Ruby’s Queue
doesn’t have a built-in concept of “closing” like Go’s channels. Instead, we simply stop adding elements and the loop naturally terminates when the queue is empty.
This example also illustrates that it’s possible to add elements to a queue and then process them all, which is conceptually similar to closing a non-empty channel in Go and still receiving the remaining values.