Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
There's another kind of loop in Ruby called the 'for' loop. The for loop is a common kind of loop in other programming languages but it functions a little bit differently in Ruby. A Ruby for loop is more of an iterator and functions internally like the each method.
A Note About For Loops
Most Ruby programmers don't use the for loop very often, instead preferring to use an "each" loop and do iteration. The reason for this is that the variables used to iterate in the for loop exist outside the for loop, while in other iterators, they exist only inside the block of code thatβs running.
You can use whichever you prefer but it's important to know how for loops work in your career as a Ruby programmer.
Code Samples
The following for
loop creates a Range
class with the numbers 1 to 3 and then passes it to the block:
for item in 1..3 do
puts "The current item is #{item}."
end
The for
loop also works on arrays:
for item in ["Programming", "is", "fun"]
puts "The current item is #{item}."
end
It's important to note that the variable will exist outside of the for
loop after it runs.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up