DEV Community

Annie Huynh
Annie Huynh

Posted on

Looping over an array or a hash

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 }

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)