A.13 Looping through Arrays
A.13.1 .each
Array#each do |Object|
# ruby code here
end
⇒ Array
Given an array, the .each
method will loop through each element of the array starting with the very first one.
Returns the Array
the method was called on.
"Chicago", "LA", "NYC"]
cities = [do |city|
cities.each
p cityend
"Chicago"
"LA"
"NYC"
The block variable city
holds the value of the elements in the array cities
. It starts with the first element "Chicago"
and then changes with each interation, holding the value of the next element ("LA"
) in the array and so on.
A.13.2 .each_with_index
Array#each_with_index do |Object, Integer|
# ruby code here
end
⇒ Array
To keep a track of the iteration number while looping through an array, .each_with_index
creates an additional block variable that starts of counting the iteration number starting at zero. After each execution of the code within the block, the block variable is incremented by 1.
do |city, count|
cities.each_with_index " " + city
p count.to_s + end
"0 Chicago"
"1 LA"
"2 NYC"
city
holds the value of elements in the array cities
. count
holds the index of the element that city
currently holds.
Note:
Variables created as a block variables can only be used within that block (between do
and end
). Using that variable outside that block will throw an error.