Ruby Iterators
Published Jul 27, 2021Updated Sep 9, 2021
Contribute to Docs
Iterators are used to do one thing multiple times. They are used in tandem with collections (Hashes, Arrays, etc…). A collection is an object that stores a group of data members.
Each Iterator
Returns all elements in a range, array or hash. Values are returned in the order they are stored in the collection.
letters = ['C', 'o', 'd', 'e', 'c', 'a', 'd', 'e', 'm', 'y']letters.each do|letter|puts letterend
- Our collection,
letters, is an array. - The
eachis a method that iterates through the collection. - The
doandendare used to indicate the scope of theeachmethod. letteris a variable that is used to store the value of each iteration.
The output would be:
C
o
d
e
c
a
d
e
m
y
Collect Iterator
Runs on all the elements in a collection. Returns the entire collection.
numbers = [1, 2, 3, 4, 5]numbers_squared = numbers.collect {|number| number * number}puts numbers_squared# Output: [1, 4, 9, 16, 25]
- The
collectmethod is a method that iterates through thenumbersarray. numberis a variable that is used to store the value of each iteration.
Times Iterator
This iterator is a loop designed to repeat a block of code a certain number of times. May or may not use an iteration variable.
5.times do |i|puts "Message number #{i + 1}"end
5.timesis the specified number of times to repeat the block of code.
The output would be:
Message number 1
Message number 2
Message number 3
Message number 4
Message number 5
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Ruby on Codecademy
- Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
- Beginner Friendly.9 hours
- Learn the basics of building applications with this convenient and powerful web development framework.
- With Certificate
- Intermediate.6 hours