Implicit return
In Ruby, methods and blocks return the value of the last evaluated expression.
def shop_menu(items_and_prices)
items_and_prices.map do |item, price|
formatted_price = format("%.2f", price)
"#{item.to_s.capitalize}: $#{formatted_price}"
end.join("\n")
end
puts shop_menu({ apple: 0.5, banana: 0.3, cherry: 0.2 })
# Output:
# Apple: $0.50
# Banana: $0.30
# Cherry: $0.20
function shopMenu(itemsAndPrices) {
return Object.entries(itemsAndPrices).map(([item, price]) => {
const capitalized = item.charAt(0).toUpperCase() + item.slice(1);
const formattedPrice = price.toFixed(2);
return `${capitalized}: $${formattedPrice}`;
}).join("\n");
}
console.log(shopMenu({ apple: 0.5, banana: 0.3, cherry: 0.2 }));
// Output:
// Apple: $0.50
// Banana: $0.30
// Cherry: $0.20
Doesn't the Ruby code here feel so much cleaner? Once you get used to it, explicit return statements feel verbose and noisy.
If you're coming from other languages that require them, it can take some time to kick the habit. Luckily, linters like RuboCop can auto-format code to ease the transition.
You can still use return in Ruby to exit early from a method... or even a file 🤫
History
Functional programming languages have pretty much universally embraced this style of implicit returns, with e.g. Lisp and Scheme doing it since the 1970's.
In the world of imperative languages explicit returns have been the norm. Though some modern languages have been caught flirting. Swift does implicit returns for one-line functions and Rust does implicit returns if you omit the semicolon at the end of an expression.
Modern JavaScript has a variant of => that does implicit returns for single expressions as well, leading to interesting behaviours like wrapping methods in parenthesis instead of curly braces to circumvent the need for explicit return even on multiline expressions 🙃.