0
0
RubyHow-ToBeginner · 3 min read

How to Return Value from Method in Ruby: Simple Guide

In Ruby, you return a value from a method by using the return keyword followed by the value, or simply by placing the value as the last line of the method. Ruby automatically returns the last evaluated expression if return is not explicitly used.
📐

Syntax

A Ruby method returns a value using the return keyword or by default returns the last evaluated expression.

  • def method_name: starts the method definition.
  • return value: explicitly returns value and exits the method.
  • If return is omitted, Ruby returns the last expression automatically.
  • end: ends the method definition.
ruby
def method_name
  # some code
  return value  # explicit return
end

# or

def method_name
  value  # implicit return of last expression
end
💻

Example

This example shows a method that returns a greeting message using implicit return and another using explicit return.

ruby
def greet(name)
  "Hello, #{name}!"  # implicit return
end

puts greet("Alice")


def add(a, b)
  return a + b  # explicit return
end

puts add(3, 4)
Output
Hello, Alice! 7
⚠️

Common Pitfalls

One common mistake is using return inside blocks or loops expecting it to return from the method, but it may cause unexpected behavior. Another is forgetting that Ruby returns the last expression automatically, so adding return is optional but can improve clarity.

ruby
def check_number(num)
  if num > 0
    return "Positive"  # explicit return exits method here
  end
  "Non-positive"  # implicit return if above condition is false
end

puts check_number(5)    # Outputs: Positive
puts check_number(-1)   # Outputs: Non-positive
Output
Positive Non-positive
📊

Quick Reference

Remember these tips when returning values from Ruby methods:

  • Use return to exit early with a value.
  • Omit return to return the last evaluated expression.
  • Methods always return a value, even if return is not used.
  • Be careful with return inside blocks as it affects method flow.

Key Takeaways

Ruby methods return the last evaluated expression by default without needing return.
Use the return keyword to exit a method early with a specific value.
Every Ruby method returns a value, even if return is not explicitly used.
Be cautious using return inside blocks as it can exit the whole method unexpectedly.
Explicit return improves code clarity but is optional for simple methods.