- Read Tutorial
- Watch Guide Video
If you're coming from other programming languages, you may already be familiar with 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 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 collection 0...42
is a shortened way of creating an array of integers and essentially we are asking the variable i
to iterate through this collection and print its own value.
So, this is how you can use for-in
loops to iterate through collections in Ruby.