Foundations
Variables
Ruby variables can hold numbers and strings, then feed later expressions.
variable assignment
A variable name stores the result of the expression on the right side of `=`.
Variables
variables.rb
Replay: real traced execution (multi-file project)
unit_price = 12
quantity = 3
total = unit_price * quantity
puts "unit=#{unit_price}"
puts "total=#{total}"
unit_price = 8
quantity = 3
total = unit_price * quantity
puts "unit=#{unit_price}"
puts "total=#{total}"
unit_price = 20
quantity = 3
total = unit_price * quantity
puts "unit=#{unit_price}"
puts "total=#{total}"
unit_price ← 12, quantity ← 3, total ← 36
1unit_price→ 12 = 12 #@unit_price=8, 202quantity→ 3 = 33total→ 36 = unit_price12 * quantity345puts "unit=#{unit_price12}"6puts "total=#{total36}"outputunit=12 total=36
unit_price ← 8, quantity ← 3, total ← 24
1unit_price→ 8 = 82quantity→ 3 = 33total→ 24 = unit_price8 * quantity345puts "unit=#{unit_price8}"6puts "total=#{total24}"outputunit=8 total=24
unit_price ← 20, quantity ← 3, total ← 60
1unit_price→ 20 = 202quantity→ 3 = 33total→ 60 = unit_price20 * quantity345puts "unit=#{unit_price20}"6puts "total=#{total60}"outputunit=20 total=60
Follow the Total
unit_pricestarts at12.quantitystarts at3.total = unit_price * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit=12andtotal=36. | unit_price | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |
Exercise: variables.rb
Reproduce unit=12 and total=36, then try unit_price 8 and 20 and predict each total before running it.