Blocks and Methods
Method Return
Methods can return early for guard cases or let the final expression become the result.
Method Return
method_return.rb
def shipping_cost(item_count)
return 0 if item_count <= 0
return 12 if item_count > 5
item_count * 2
end
item_count =
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 =
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 =
cost = shipping_cost(item_count)
puts "item_count=#{item_count}"
puts "cost=#{cost}"
method return
An explicit `return` exits the method immediately; otherwise Ruby returns the final expression.