Foundations
Arrays
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
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}"
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
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
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
scoresstarts as[82, 91, 76].first_score = scores[0]reads82.scores.sumadds82 + 91 + 76.totalbecomes249.- Integer division makes
averageequal83, so the program printsfirst=82andaverage=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.