- Arrays are like a list of things.
- They maintain elements in order and identify each element with an index number.
- The first element is at index 0.
- The second at index 1, and so on.
loop through array ruby
Example 1
list = ['Alice', 'Adam', 'Dean', 'Daniel'] list.each do |name| puts "Hey #{name}! How are You?" end
The Above Code Outputs the
# Hey Alice! How are You? # Hey Adam! How are You? # Hey Dean! How are You? # Hey Daniel! How are You?
Example 2
- The below code iterate through all the elements giving you the value and the index.
list = ['Alice', 'Adam', 'Dean', 'Daniel'] list.each_with_index do |name,index| puts "#{index} / Hey #{name}! How are You?" end
The Above Code Outputs the
# 0 / Hey Alice! How are You? # 1 / Hey Adam! How are You? # 2 / Hey Dean! How are You? # 3 / Hey Daniel! How are You?