Ruby Return Values
Every Ruby method returns something. Understanding what it returns — and when — helps you write short, chainable code and avoid surprises with nil.
The last expression is the return value
def shipping_cost(weight)
base = 4.5
base + weight * 1.2
end
def status(paid)
if paid
"confirmed"
end
end
p shipping_cost(5)
p status(true)
p status(false)10.5
"confirmed"
nil
When paid is false, no branch of the if runs, so the if evaluates to nil — and that becomes the return value. Remember this when an if without else is the last line of a method.
Explicit return
return exits the method immediately with the given value. Its most common use is a guard clause that handles special cases first:
def discount(price, code)
return price if code.nil?
return price * 0.9 if code == "SAVE10"
return 0 if code == "FREEBIE"
price
end
p discount(50, nil)
p discount(50, "SAVE10")
p discount(50, "FREEBIE")
p discount(50, "UNKNOWN")50
45.0
0
50
Ruby style: write return only for early exits; let the last line return implicitly.
Returning multiple values
A method can only return one object, but that object can be an array. With multiple assignment, it feels like returning several values:
def min_max_avg(numbers)
[numbers.min, numbers.max, numbers.sum.fdiv(numbers.size)]
end
low, high, avg = min_max_avg([4, 9, 2, 7])
puts "low=#{low} high=#{high} avg=#{avg}"
def split_name(full)
return full.split(" ", 2)
end
first, last = split_name("Maria de la Cruz")
p first, lastlow=2 high=9 avg=5.5
"Maria"
"de la Cruz"
return a, b (with a comma) also returns an array [a, b].
Returning a hash
When the values have meanings, a hash is clearer than an array:
def analyse(text)
words = text.split
{
words: words.size,
longest: words.max_by(&:length),
shouting: text == text.upcase,
}
end
result = analyse("Ruby makes programmers smile")
p result
p result[:longest]{words: 4, longest: "programmers", shouting: false}
"programmers"
What common methods return
Knowing return values lets you chain calls. Some surprises are worth memorising:
p puts("x") # puts returns nil
p [1, 2].each { } # each returns the receiver
p [1, 2].map { |n| n } # map returns a new array
p "a".concat("b") # concat returns the string
p({a: 1}.delete(:a)) # delete returns the removed value
p [3, 1].sort! # sort! returns the array...
p [1, 2].uniq! # ...but uniq! returns nil if nothing changed
x = (y = 5) # assignment returns the assigned value
p xx
nil
[1, 2]
[1, 2]
"ab"
1
[1, 3]
nil
5
Chaining
Because methods return objects, you can call the next method on the result directly:
sentence = " the quick brown fox jumps "
result = sentence.strip.split.map(&:capitalize).reject { |w| w.length < 4 }.join(" ")
p result
total = [12.5, 8, 30].sum.then { |s| s * 1.21 }.round(2)
p total"Quick Brown Jumps"
61.11
then passes the value to a block and returns the block's result — useful for continuing a chain with a calculation.
return inside blocks
return inside a block returns from the surrounding method, not just the block. Use next to finish a single block iteration with a value:
def first_negative(numbers)
numbers.each do |n|
return n if n.negative?
end
nil
end
p first_negative([3, -2, -7])
p first_negative([1, 2])
doubled = [1, 2, 3].map do |n|
next 0 if n == 2
n * 2
end
p doubled-2
nil
[2, 0, 6]
| Keyword | Inside a block it… |
|---|---|
next value |
ends this iteration; value is the block's result |
break value |
stops the iterator; value becomes the iterator's return value |
return value |
returns from the enclosing method |
Test yourself
What does def f; if false; 1; end; end return when called?
- 1
- false
- nil
- An error
What does [1, 2, 3].each { |n| n * 2 } return?
- [2, 4, 6]
- [1, 2, 3]
- nil
- 6
How does a, b = method_returning_array work?
- It raises an error
- The array is unpacked into a and b
- Both get the whole array
- Only a is assigned