For in Ruby
Ruby provides several ways to create loops. Here are some basic types of loops in Ruby.
To run the program, save it as loops.rb
and use the ruby
command:
Ruby offers various looping constructs, including while
, until
, for
, loop
, and iterator methods like times
and each
. The while
loop is similar to the basic condition-only loop in other languages. The times
method provides a simple way to repeat an action a specific number of times. The each
method, often used with ranges or arrays, is a powerful and idiomatic way to iterate in Ruby.
The loop
method creates an infinite loop that continues until explicitly broken. The next
keyword in Ruby is equivalent to continue
in many other languages, allowing you to skip to the next iteration.
We’ll see some other loop forms later when we look at iterating over collections, working with blocks, and other data structures.