Ruby arrays keep ordered values that can be indexed, counted, and combined.

array An array stores values in order, and indexing starts at `0`.

Arrays

scores
arrays.rb
Replay: real traced execution (multi-file project)
scores = [82, 91, 76]
first_score = scores[0]
total = scores.sum
average = total / scores.length

puts "first=#{first_score}"
puts "average=#{average}"
scores = [100, 95, 90]
first_score = scores[0]
total = scores.sum
average = total / scores.length

puts "first=#{first_score}"
puts "average=#{average}"
scores = [60, 70, 80]
first_score = scores[0]
total = scores.sum
average = total / scores.length

puts "first=#{first_score}"
puts "average=#{average}"
  1. scores ← [82, 91, 76], first_score ← 82, total ← 249, average ← 83

    1scores→ [82, 91, 76] = [82, 91, 76]  #@scores=[100, 95, 90], [60, 70, 80]2first_score→ 82 = scores[0]823total→ 249 = scores.sum2494average→ 83 = total249 / scores.length356puts "first=#{first_score82}"7puts "average=#{average83}"
    outputfirst=82
    average=83
  1. scores ← [100, 95, 90], first_score ← 100, total ← 285, average ← 95

    1scores→ [100, 95, 90] = [100, 95, 90]2first_score→ 100 = scores[0]1003total→ 285 = scores.sum2854average→ 95 = total285 / scores.length356puts "first=#{first_score100}"7puts "average=#{average95}"
    outputfirst=100
    average=95
  1. scores ← [60, 70, 80], first_score ← 60, total ← 210, average ← 70

    1scores→ [60, 70, 80] = [60, 70, 80]2first_score→ 60 = scores[0]603total→ 210 = scores.sum2104average→ 70 = total210 / scores.length356puts "first=#{first_score60}"7puts "average=#{average70}"
    outputfirst=60
    average=70

Follow the Array

  1. scores starts as [82, 91, 76].
  2. first_score = scores[0] reads 82.
  3. scores.sum adds 82 + 91 + 76.
  4. total becomes 249.
  5. Integer division makes average equal 83, so the program prints first=82 and average=83. | scores | first | total | average | | --- | --- | --- | --- | | 100, 95, 90 | 100 | 285 | 95 | | 82, 91, 76 | 82 | 249 | 83 | | 60, 70, 80 | 60 | 210 | 70 |

Exercise: arrays.rb

Reproduce first=82 and average=83, then try one listed score array and predict its first score and average.