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

item_count
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}"
  1. item_count ← 3

    8item_count→ 3 = 3  #@item_count=0, 79cost = shipping_cost(item_count3)
  2. 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 * 26end
  3. cost ← 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
  1. item_count ← 0

    8item_count→ 0 = 09cost = shipping_cost(item_count0)
  2. 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 * 26end
  3. cost ← 0

    8item_count = 09cost→ 0 = shipping_cost(item_count0)1011puts "item_count=#{item_count0}"12puts "cost=#{cost0}"
    outputitem_count=0
    cost=0
  1. item_count ← 7

    8item_count→ 7 = 79cost = shipping_cost(item_count7)
  2. 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 * 26end
  3. cost ← 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

  1. item_count starts as 3.
  2. The <= 0 guard is false, so cost is not 0.
  3. The > 5 check is false, so cost is not 12.
  4. The final path uses item_count * 2.
  5. The method returns 6, so the program prints cost=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.