Loop
Ruby focuses on natural and expressive syntax. A simple but clear-cut example of this is the loop do ... end construct for creating infinite loops. Let's contrast this with the conventional while(true) { ... } construct found in most languages.
loop do # do some work print "." end
while(true) {
// do some work
process.stdout.write(".");
}
The Ruby version reads like human language. It communicates the intention of creating a loop,
without additional noise. The comparison, on the other hand, communicates computer logic.
Under the hood
Under the hood, Ruby's loop syntax isn't a dedicated keyword. It's a regular method defined on the Kernel module that takes a block and repeatedly yields to it. Its implementation is approximately:
def loop
while true
yield
end
rescue StopIteration => e
e.result
end
Note how loop relies on a conventional while true loop behind the scenes, with some added code for block yielding and graceful iteration termination. This overhead implies that loop do is less performant than the foundational while true loop. However, that is precisely the kind of trade-off that is gladly made in idiomatic Ruby to optimise for humans rather than computers.
History
Ruby wasn't the first language to introduce loop syntax. Ada, Eiffel and Common Lisp are examples of languages that had similar constructs before Ruby's inception in the mid-1990s. Ruby also wasn't the last language to introduce such a construct. Notably Rust reserves a dedicated keyword for loop.