Skip to content
AgileLogics
5 min read

Return Values

Prerequisites: Methods

Every Ruby method returns a value. By default it's the value of the last expression that ran.

def double(n)
  n * 2
end

result = double(21)
p result
42

Returning early with return

return exits the method immediately. It's most useful for guard clauses — checks at the top of a method that bail out early:

def discount(price, code)
  return price if code.nil?
  return price * 0.9 if code == "SAVE10"

  price
end

p discount(100, nil)
p discount(100, "SAVE10")
p discount(100, "WRONG")
100
90.0
100

Guard clauses keep the main logic un-indented and easy to read, instead of wrapping it in nested ifs.

Returning several values

Return an array, and the caller can unpack it into several variables:

def min_max(numbers)
  [numbers.min, numbers.max]
end

low, high = min_max([4, 9, 1])
puts "#{low} to #{high}"
1 to 9

puts is not return

puts prints a value; it doesn't return it. puts itself returns nil:

def shout(word)
  puts word.upcase
end

result = shout("hi")
p result
HI
nil

Common mistakes

  • Ending a method with puts and then trying to use its result. Let methods return values, and print them where they're called.
  • An if with no else as the last line returns nil when the condition is false.

Practice

Write grade(score) that returns "pass" or "fail" (pass is 50 or more) using a guard clause, and print the results for 72 and 31.

Show solution
def grade(score)
  return "pass" if score >= 50

  "fail"
end

puts grade(72)
puts grade(31)