The for...in loops tutorial
If you're coming from other programming languages, you may already be familiar with the for
loops. Ruby also has these types of loops; however, they are not used frequently in real-world applications. This is mainly because the each
loop is more popular and easier to work with.
With that being said, it's still good to learn about the for
loops to know all your available options provided in the language. Also, in this lesson, I'm going to show you an easy way to create an array of integers.
The syntax for a for...in
loop is:
for i in 0...42 p i end
If you run this program, your output should look like this:

In the code, i
is our iterator variable, and its value starts at 0
. The 0...42
collection is a shortened way of creating an array of integers, and essentially, we are asking the i
variable to iterate through this collection and print its own value.
So, this is how you can use the for...in
loops to iterate through collections in Ruby.