How to Return a Value from a Ruby Method
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
def <name>(<parameters>)
<expression> # the last expression is the result
end
def <name>(<parameters>)
return <value> if <condition> # leave early
<expression>
end
| Part | What it does |
|---|---|
| Last expression | Its 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:

def grade(score)
if score >= 50
'pass'
else
'fail'
end
end
puts grade(72)
puts grade(31)
Step 2: Run It
ruby main.rb
pass
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
| Mistake | What happens | Do this instead |
|---|---|---|
Ending a method with puts | The method prints, then returns nil, because puts returns nil | Let the value be the last expression, and print it outside |
| Adding a line after the value you meant to return | The new last line's value is returned instead | Keep the result last, or use return |
return in every method out of habit | Noise | Use it for early exits only |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A method returns nil | Its last expression is puts, or an if without a matching branch | Make the wanted value the last expression |
| A method returns the wrong value | A later line became the last expression | Move 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
- Return values, in the Ruby documentation.
