Blocks and Methods
Method Return
Methods can return early for guard cases or let the final expression become the result.
method return
An explicit `return` exits the method immediately; otherwise Ruby returns the final expression.
Method Return
method_return.rb
Replay: real traced execution (multi-file project)
def shipping_cost(item_count)
return 0 if item_count <= 0
return 12 if item_count > 5
item_count * 2
end
item_count = 3
cost = shipping_cost(item_count)
puts "item_count=#{item_count}"
puts "cost=#{cost}"
def shipping_cost(item_count)
return 0 if item_count <= 0
return 12 if item_count > 5
item_count * 2
end
item_count = 0
cost = shipping_cost(item_count)
puts "item_count=#{item_count}"
puts "cost=#{cost}"
def shipping_cost(item_count)
return 0 if item_count <= 0
return 12 if item_count > 5
item_count * 2
end
item_count = 7
cost = shipping_cost(item_count)
puts "item_count=#{item_count}"
puts "cost=#{cost}"
item_count ← 3
8item_count→ 3 = 3 #@item_count=0, 79cost = shipping_cost(item_count3)def shipping_cost(item_count)
1def shipping_cost(item_count3)2 return 0 if item_count3 <= 03 return 12 if item_count3 > 545 item_count3 * 26endcost ← 6
8item_count = 3 #@item_count=0, 79cost→ 6 = shipping_cost(item_count3)1011puts "item_count=#{item_count3}"12puts "cost=#{cost6}"outputitem_count=3 cost=6
item_count ← 0
8item_count→ 0 = 09cost = shipping_cost(item_count0)def shipping_cost(item_count)
1def shipping_cost(item_count0)2 return 0 if item_count0 <= 03 return 12 if item_count0 > 545 item_count0 * 26endcost ← 0
8item_count = 09cost→ 0 = shipping_cost(item_count0)1011puts "item_count=#{item_count0}"12puts "cost=#{cost0}"outputitem_count=0 cost=0
item_count ← 7
8item_count→ 7 = 79cost = shipping_cost(item_count7)def shipping_cost(item_count)
1def shipping_cost(item_count7)2 return 0 if item_count7 <= 03 return 12 if item_count7 > 545 item_count7 * 26endcost ← 12
8item_count = 79cost→ 12 = shipping_cost(item_count7)1011puts "item_count=#{item_count7}"12puts "cost=#{cost12}"outputitem_count=7 cost=12
Follow the Method
item_countstarts as3.- The
<= 0guard is false, so cost is not0. - The
> 5check is false, so cost is not12. - The final path uses
item_count * 2. - The method returns
6, so the program printscost=6. | item_count | path | cost | | --- | --- | --- | | 3 | multiply by 2 | 6 | | 0 | guard return | 0 | | 7 | over 5 return | 12 |
Exercise: method_return.rb
Reproduce item_count=3 and cost=6, then use the pinned item_count variants to predict costs 0 and 12.