Ruby Return
Understanding how methods return values in Ruby
↩️ What is Return in Ruby?
Return sends a value back from a method. Ruby automatically returns the last evaluated expression, making your code clean and concise without explicit return statements.
# Implicit return
def add(a, b)
a + b # Automatically returned
end
puts add(3, 5)
Output:
8
Key Return Concepts
Implicit Return
Last line is automatically returned
def square(n)
n * n
end
Explicit Return
Use 'return' keyword when needed
def check(n)
return "negative" if n < 0
"positive"
end
Early Exit
Return stops method execution
def validate(age)
return false if age < 0
true
end
Multiple Values
Return arrays or hashes
def stats
[10, 20, 30]
end
🔹 Implicit Return
Ruby automatically returns the last evaluated expression in a method. This feature makes code cleaner and more readable by eliminating unnecessary return keywords, following Ruby's principle of developer happiness.
# Simple implicit return
def double(number)
number * 2
end
puts double(7)
# Multiple lines, last one returned
def calculate
x = 10
y = 20
x + y # This is returned
end
puts calculate
# Expression result is returned
def is_adult?(age)
age >= 18 # Boolean result returned
end
puts is_adult?(25)
puts is_adult?(15)
Output:
14
30
true
false
🔹 Explicit Return
The 'return' keyword explicitly exits a method and sends back a value. Use it for early exits, guard clauses, or when you want to make your intention crystal clear to other developers.
# Explicit return keyword
def subtract(a, b)
return a - b
end
puts subtract(10, 3)
# Return with condition
def grade(score)
return "A" if score >= 90
return "B" if score >= 80
return "C" if score >= 70
"F"
end
puts grade(95)
puts grade(82)
puts grade(65)
Output:
7
A
B
F
🔹 Early Return Pattern
Early returns help handle edge cases and validations at the start of methods. This pattern improves code readability by dealing with special conditions first, then focusing on the main logic without deep nesting.
# Guard clause pattern
def divide(a, b)
return "Cannot divide by zero" if b == 0
a / b
end
puts divide(10, 2)
puts divide(10, 0)
# Multiple guard clauses
def process_user(name, age)
return "Name required" if name.nil? || name.empty?
return "Invalid age" if age < 0
return "Too young" if age < 18
"User #{name} processed successfully"
end
puts process_user("Alice", 25)
puts process_user("", 30)
puts process_user("Bob", 15)
Output:
5
Cannot divide by zero
User Alice processed successfully
Name required
Too young
🔹 Returning Multiple Values
Ruby methods can return multiple values using arrays or hashes. This is useful when you need to send back related data together, like coordinates, statistics, or calculation results with metadata.
# Return array
def min_max(numbers)
[numbers.min, numbers.max]
end
min, max = min_max([3, 7, 1, 9, 4])
puts "Min: #{min}, Max: #{max}"
# Return hash
def user_info(name, age)
{ name: name, age: age, status: "active" }
end
info = user_info("John", 30)
puts "Name: #{info[:name]}, Age: #{info[:age]}"
# Return multiple with explicit values
def calculate_stats(num)
[num * 2, num * 3, num * 4]
end
double, triple, quadruple = calculate_stats(5)
puts "Double: #{double}, Triple: #{triple}, Quad: #{quadruple}"
Output:
Min: 1, Max: 9
Name: John, Age: 30
Double: 10, Triple: 15, Quad: 20
🔹 Return with Nil
Methods return nil when there's no explicit value or when execution reaches the end without a value. Understanding nil returns helps prevent bugs and makes your code more predictable and robust.
# Method returns nil
def print_message
puts "Hello"
# No return value, returns nil
end
result = print_message
puts "Result: #{result.inspect}"
# Explicit nil return
def find_user(id)
return nil if id < 0
"User #{id}"
end
puts find_user(5)
puts find_user(-1).inspect
# Conditional nil
def get_discount(amount)
return nil if amount < 100
amount * 0.1
end
puts get_discount(150)
puts get_discount(50).inspect
Output:
Hello
Result: nil
User 5
nil
15.0
nil