Loops repeat a small block of work for each value in a range.

each loop `each` visits every value in a collection or range.

Loops

limit
loops.rb
Replay: real traced execution (multi-file project)
limit = 4
total = 0

(1..limit).each do |number|
  total += number
end

puts "limit=#{limit}"
puts "total=#{total}"
limit = 2
total = 0

(1..limit).each do |number|
  total += number
end

puts "limit=#{limit}"
puts "total=#{total}"
limit = 6
total = 0

(1..limit).each do |number|
  total += number
end

puts "limit=#{limit}"
puts "total=#{total}"
  1. limit ← 4, total ← 0

    1limit→ 4 = 4  #@limit=2, 62total→ 0 = 034(1..limit4).each do |number|5  total += number6end
  2. do |number|

    pass 1 of 4
    4(1..limit).each do |number1|5  total0 += number16end
    All 4 passes — pass 1 is the card above
    passnumbertotallimit
    110
    221
    333
    4464
  3. puts "limit=#{limit}"

    8puts "limit=#{limit4}"9puts "total=#{total10}"
    outputlimit=4
    total=10
  1. limit ← 2, total ← 0

    1limit→ 2 = 22total→ 0 = 034(1..limit2).each do |number|5  total += number6end
  2. do |number|

    pass 1 of 2
    4(1..limit).each do |number1|5  total0 += number16end
  3. do |number|

    pass 2 of 2
    4(1..limit2).each do |number2|5  total1 += number26end
  4. puts "limit=#{limit}"

    8puts "limit=#{limit2}"9puts "total=#{total3}"
    outputlimit=2
    total=3
  1. limit ← 6, total ← 0

    1limit→ 6 = 62total→ 0 = 034(1..limit6).each do |number|5  total += number6end
  2. do |number|

    pass 1 of 6
    4(1..limit).each do |number1|5  total0 += number16end
    All 6 passes — pass 1 is the card above
    passnumbertotallimit
    110
    221
    333
    446
    5510
    66156
  3. puts "limit=#{limit}"

    8puts "limit=#{limit6}"9puts "total=#{total21}"
    outputlimit=6
    total=21

Follow the Loop

  1. limit starts at 4.
  2. total starts at 0.
  3. The range (1..limit) visits 1, 2, 3, and 4.
  4. Each number is added to total.
  5. The program prints limit=4 and total=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |

Exercise: loops.rb

Reproduce total=10 for limit 4, then try limit 2 and 6 and predict each total before running it.