For In Loops in Ruby Tutorial
If you're coming from other programming languages, you should be familiar with For loops. Ruby also has these loops, but they are not used frequently in real-world applications. This is mainly because the Each loop is more popular and easier to work with.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

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:

large

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.