Range Over Channels in Ruby

Our first example demonstrates how to iterate over values received from a channel. Here’s the full source code:

# We'll iterate over 2 values in the `queue` channel.
queue = Queue.new
queue << "one"
queue << "two"

# This loop iterates over each element as it's
# received from `queue`. Because we close the
# queue after adding elements, the iteration terminates
# after receiving the 2 elements.
until queue.empty?
  elem = queue.pop
  puts elem
end

To run the program, save the code in a file (e.g., range_over_queue.rb) and use the ruby command:

$ ruby range_over_queue.rb
one
two

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.