Skip to main content

How to Return a Value from a Ruby Method

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A Ruby method returns the value of the last expression it ran, so most methods never write return. Even an if has a value: the branch it picked, which makes it the method's result.

Syntax​

Syntax
def <name>(<parameters>)
<expression> # the last expression is the result
end

def <name>(<parameters>)
return <value> if <condition> # leave early
<expression>
end
PartWhat it does
Last expressionIts value is what the method returns.
return <value>Returns straight away, skipping the rest of the method.

The Ruby methods documentation: "By default, a method returns the last expression that was evaluated in the body of the method." And: "The return keyword can be used to make it explicit that a method returns a value. It can also be used to make a method return before the last expression is evaluated."

The Example​

The example grades a score: pass from 50 up, fail below. The if is the last expression, so its chosen branch is the result.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Method​

Create a file named main.rb:

main.rb, which defines grade(score) with an if that gives pass when score >= 50 and fail otherwise, and puts grade(72) and grade(31).

main.rb
def grade(score)
if score >= 50
'pass'
else
'fail'
end
end

puts grade(72)
puts grade(31)

Step 2: Run It​

Terminal
ruby main.rb
Output
pass
fail

A zsh terminal where ruby main.rb prints pass and fail.

The command is the same in zsh, bash and PowerShell.

Returning Early​

return shines for leaving a method before the end. A method with return 'negative' if n < 0 before its last line returned negative for -1 and fine for 1.

Common Mistakes​

MistakeWhat happensDo this instead
Ending a method with putsThe method prints, then returns nil, because puts returns nilLet the value be the last expression, and print it outside
Adding a line after the value you meant to returnThe new last line's value is returned insteadKeep the result last, or use return
return in every method out of habitNoiseUse it for early exits only

Troubleshooting​

SymptomLikely causeFix
A method returns nilIts last expression is puts, or an if without a matching branchMake the wanted value the last expression
A method returns the wrong valueA later line became the last expressionMove the value to the end

FAQ​

What does an if without else return when the condition is false?​

nil, so the method returns nil too.

Can a method return several values?​

Yes: return a, b returns the array [a, b], which the caller can split with x, y = method_name.

Conclusion​

A Ruby method returns its last expression, including the branch an if chose. Use return to leave early, and keep the value you want last.

Additional Resources​