Looping over an array or a hash = iterate over it.
Iterating Over Arrays
Example:
numbers = [1, 2, 3, 4, 5]
numbers.each { |element| puts element }
The example above is saying: "Take this array (numbers) and for each element in the array, print it to the console.
The variable name inside the two | | characters represents the individual items in the array. After the .each method passes through the items, each item is assigned to the variable name.
An alternative syntax is do..end for blocks of code:
numbers.each do |number|
puts number
end
The convention is to use {} when the block is short and fits on one line, and do..end for longer blocks that span multiple lines.
Iterating Over Multidimensional Arrays
You can access a specific element by typing array[position of first element][position of second element]
Syntax for iterating over multidimensional arrays:
s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
s.each {|sub_array|
sub_array.each {|element| puts element}}
Iterating Over Hashes
When iterating over hashes you need two placeholder variables to represent each key/value pair.
The syntax is as follows:
restaurant_menu = {
"noodles" => 4,
"soup" => 3,
"salad" => 2
}
restaurant_menu.each do |item, price|
puts "#{item}: #{price}"
end
The iterator loops through the restaurant_menu hash and assign the key to item and the value to price for each iteration.
Top comments (0)