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
The while loop will print out an array and use a variable to increment and keep track of what it is printing out. As we're looping through each item in the array, we're using a specific pattern -- getting an item out of the array and working with it in a specific way. You could say that we're iterating over each item in the array. Ruby gives us ways to do this without writing a loop each time. The "each" method is commonly used to iterate over a collection of items, like an array.
Documentation Links
Code Samples
Given the following array:
array = [0, 1, 2, 3, 4, 5]
We can use the each
method to iterate over the individual items in the array:
array.each do |item|
puts "The current array item is: #{item}"
end
The do...end
is called a block. A block is a chunk of code you can pass into a Ruby method. What the each
method does is to call your block once for each item in the array, and pass the item into the block as an argument. So the above block prints each item in the array on its own line.
The block can also be written on one line:
array.each {|item| puts "The current array item is: #{item}"}
It is conventional to write blocks using the do...end
syntax for multiple lines of code in the block and the braces {}
syntax for single line code blocks.
We can also manipulate items inside of an each
block:
array = [0, 1, 2, 3, 4, 5]
array.each do |item|
item = item + 2
puts "The current item + 2 is #{item}."
end
This will leave the original array unchanged.
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