Explain it simply
Explain it simply
Think of a method as a recipe card. You write the steps once and give the card a name, then every time you want that dish you just say the name and hand over the ingredients. The ingredients are the arguments, and the finished dish is the value the method gives back.
In Ruby a method starts with def and finishes with end. The nice surprise is that you almost never write return: whatever the last line of the method evaluates to is handed back automatically. That is why greet("Aung") can simply end with a string and still give you the greeting.
Problem → Why → Solution
The problem: the method answers nil instead of a number
Imagine a small script that prints a price with tax. You write a method called full_price that calculates the total and prints it, then you try to use the answer on the next line. Instead of a number you get a crash, because the method ended with puts, and puts always evaluates to nil.
Ruby does not complain when a method prints instead of returns. It only fails later, at the place that tries to use the missing value, which can be far from the real cause.
def full_price(price, tax)
total = price + price * tax
puts "Total: #{total}" # this is the last line, so nil is returned
end
result = full_price(100, 0.1)
puts result * 2 # NoMethodError: undefined method '*' for nilWhy did the method give back nil?
A method returns the value of its last expression, and puts is an expression whose value is nil. Printing and returning are two different jobs: use puts to show something to a person, and let the last line be the value itself when other code needs to use it. Once you see a method's value as its last line, the error message becomes easy to read.
Core concept: a method's value is its last expression
A method definition has three parts: the name after def, an optional list of parameters in parentheses, and a body that ends with end. Names use snake_case, and you call a method by writing its name with the arguments in parentheses. When there is no dot in front of the call, as in greet("Aung"), Ruby calls the method on the current object, which at the top of a script is a special object named main.
Every method returns the value of the last expression it evaluated. The return keyword exists for leaving early, usually as a guard at the top (return 0 if numbers.empty?), not as the last line. The same rule applies to if: a method whose last expression is an if returns the value of the branch that ran, and returns nil when no branch ran.
Parameters come in four common shapes, and you can mix them as long as you keep this order: required, optional, splat, then keywords. The table shows how each one is declared and how it is called.
| Kind | Declared as | Called as |
|---|---|---|
| Required | def add(a, b) | add(1, 2) |
| Default value | def tag(name, level = 1) | tag("x") or tag("x", 3) |
| Keyword | def box(width:, height: 1) | box(width: 4) |
| Splat | def total(*numbers) | total(1, 2, 3) |
Two punctuation marks at the end of a method name are conventions that Ruby itself does not enforce. A ? means the method answers a yes-or-no question and returns true or false, as in empty? or adult?. A ! warns that this is the more dangerous sibling of a method with the same name, usually because it changes the object in place, as sort! does while sort returns a new array. The ! is only a name, though: upcase! returns nil when nothing needed changing, and many methods that do change an object, such as push and delete, have no ! at all.
Finally, Ruby has no method overloading. If you define area twice with different parameters, the second def replaces the first, and calling area with the old argument count raises ArgumentError. Default values, keyword arguments and splats give you the flexibility that overloading gives in other languages.
- Call the name with arguments
- Arguments bind to parameters
- Body runs top to bottom
- The last expression is handed back
A method is a named block of code that always answers with its last expression, even when that answer is just nil.
General pattern
def method_name(required, optional = default, *rest, key:, other: default)
# statements run from top to bottom
last_expression # this value is returned
end
def predicate?(value) = value > 0 # endless form: one expression, no end
method_name(arg1, arg2, key: value)Parameters appear in the order required, optional, splat, keyword. The final expression of the body is the return value, so use return only to leave early. A method that is a single expression can use the endless form def name(args) = expression (Ruby 3.0 and later), and a name ending in ? should return true or false.
Example: methods that return values
The first three methods below have no return keyword at all. greet builds a string, add adds two numbers, and adult? answers a yes-or-no question, so its name ends with a question mark. The puts calls at the bottom print whatever each method returned.
Run it and match each printed line with the call that produced it. Every value you see is simply the last expression of the corresponding method.
def greet(name)
"Hello, #{name}!"
end
def add(a, b)
a + b
end
def adult?(age)
age >= 18
end
puts greet("Aung")
puts add(5, 7)
puts adult?(20)
puts adult?(12)Code breakdown
- Defining
def greet(name)def opens the method and name is a parameter: a local variable that exists only inside the method and holds whatever the caller passed in.
- Implicit return
"Hello, #{name}!"The body is a single expression, so its value is the return value. No return keyword is needed, and the #{...} part inserts name into the string.
- Operators are methods
a + ba + b is the last expression of add, so its result goes back to the caller. Ruby actually reads it as a.+(b), which is why + also works on strings and arrays.
- Predicate
def adult?(age)The ? is part of the name and tells readers the method returns true or false. Its body, age >= 18, is already a boolean, so no if is needed.
- Calling
puts add(5, 7)add(5, 7) runs first and returns 12, then puts prints that value. Nesting calls like this is normal because every method call is an expression with a value.
Hello, Aung!
12
true
falseDefault, keyword and splat arguments
Default values let callers leave an argument out. Keyword arguments, written name: value, make calls explain themselves: price_label(20, currency: "EUR") reads better than a mysterious price_label(20, "EUR", 0.1), and the order does not matter. A keyword without a default (like color:) is required, and Ruby raises an error if you forget it. A splat parameter (*numbers) collects any number of extra arguments into an array, which may be empty.
def price_label(amount, currency: "USD", tax: 0.0)
total = amount * (1 + tax)
format("%.2f %s", total, currency)
end
def average(*numbers)
return 0 if numbers.empty?
numbers.sum / numbers.size.to_f
end
puts price_label(20)
puts price_label(20, currency: "EUR", tax: 0.1)
puts average
puts average(4, 8, 15)The four puts lines print 20.00 USD, 22.00 EUR, 0 and 9.0. You can see the defaults filling in USD and a tax of 0.0, the keywords being passed by name, and average with no arguments returning 0 straight from its guard clause.
Reading ArgumentError messages
Ruby checks the argument list for you, and its messages are precise. The snippet below calls methods wrongly on purpose and prints each error message.
def add(a, b)
a + b
end
def label(text, color:)
"#{color}: #{text}"
end
attempts = [
-> { add(1) },
-> { label("hi") },
-> { label("hi", color: "red", size: 3) }
]
attempts.each do |attempt|
attempt.call
rescue ArgumentError => e
puts e.message
end| Mistake | Message printed by Ruby 4.0.9 |
|---|---|
| Too few positional arguments | wrong number of arguments (given 1, expected 2) |
| A required keyword is missing | missing keyword: :color |
| A keyword the method does not know | unknown keyword: :size |
These messages tell you exactly which call to fix, so read the given and expected numbers first. For keyword errors, the symbol name usually shows you the typo at once.
Predicates and bang methods in practice
The code below sets one predicate beside two bang methods. Notice that uniq! returns nil when there was nothing to remove and returns the array itself when there was. Compare sort with sort! too: sort gives you a new array and leaves list alone, while sort! changes list itself.
def valid_port?(port)
port.between?(1, 65_535)
end
tags = ["ruby", "web"]
p tags.uniq!
tags << "ruby"
p tags.uniq!
p tags
list = [3, 1, 2]
p list.sort
p list
p list.sort!
p list
p valid_port?(8080)
p valid_port?(70_000)The values printed are nil, ["ruby", "web"], ["ruby", "web"], [1, 2, 3], [3, 1, 2], [1, 2, 3], [1, 2, 3], true and false. The rule that follows is simple: when you want a value, use the version without the !, and use the ! version only for its in-place change without relying on what it returns.
No overloading: the last def wins
Developers coming from Java or C++ often expect two methods with the same name and different parameters to coexist. Ruby finds a method by name alone, so the second def replaces the first. The code below shows area(3) failing for that reason, followed by a flexible version that uses a default value.
def area(side)
side * side
end
def area(width, height) # this replaces the first area completely
width * height
end
begin
area(3)
rescue ArgumentError => e
puts "area(3) failed: #{e.message}"
end
puts area(3, 4)
def area_flexible(width, height = width)
width * height
end
puts area_flexible(3)
puts area_flexible(3, 4)The output is area(3) failed: wrong number of arguments (given 1, expected 2) followed by 12, 9 and 12. A default may refer to an earlier parameter, as height = width does, so one method can cover what two overloads would do elsewhere.
Mutating an argument versus reassigning it
When you pass an object to a method, you pass a reference to that object, not a copy. So list << item inside the method changes the very array the caller holds. Reassigning the parameter name, as in list = ["fresh"], only rebinds the method's local variable and leaves the caller untouched.
def add_item(list, item)
list << item # changes the caller's array
end
def replace_list(list)
list = ["fresh"] # rebinds the local name only
list
end
cart = ["tea"]
add_item(cart, "milk")
p cart
replace_list(cart)
p cartBoth lines print ["tea", "milk"] because the first call changed cart and the second did not. Unless changing the caller's data is the whole point, it is safer for a method to leave its arguments alone and return a new result.
In real projects
Where this shows up in real projects
In real Ruby code almost everything is a method call, so naming and shape matter more than they first seem. A Rails model offers valid? and save, plus save!, which raises an error instead of returning false; developers rely on the ? and ! endings to guess behavior without opening the source. Test libraries such as RSpec turn a matcher like be_empty into a call to your object's empty? method, so a predicate that returns true or false makes tests read like plain English.
Keyword arguments are common in public interfaces, because calls such as send_email(to: user.email, subject: "Welcome") document themselves and survive the day somebody adds a new optional setting. Small methods that do one job and return a value are also the easiest thing to test: you call them with some arguments and compare the result, with no screen or database involved.
Common mistakes
Common mistakes
1. Ending a method with puts and using its result
A method such as def show_total(x); puts x; end returns nil, so total = show_total(5) stores nil and a later total * 2 raises NoMethodError. Keep calculating methods free of puts and print the returned value at the call site.
2. Trusting the return value of a bang method
tags = tags.uniq! looks as if it stores the cleaned array, but uniq! returns nil when there were no duplicates, so you silently lose your data. Use the plain uniq when you want a value, and use uniq! only for the in-place change, ignoring what it returns.
3. Expecting overloading
Defining area(side) and then area(width, height) does not give you two methods. The second replaces the first, and area(3) now raises ArgumentError (wrong number of arguments (given 1, expected 2)). Use a default value such as height = width instead.
4. Leaving out an end
Every def, if and do block needs its own end. When one is missing, Ruby cannot know where you meant to close the block, so it points at the opening def and at the end of the file, with a message saying it expected an end to close the def statement. Indent consistently and let your editor match the keywords so the missing one stands out.
Best practices
Best practices
- Give each method one job and a name that says what it returns, such as total_price or adult?.
- Reserve return for early exits and let the final expression be the result.
- Switch to keyword arguments once a method takes three parameters or any true/false flag.
- Offer the version without ! first, and add the bang version only when changing an object in place is genuinely useful.
Mini challenge
Mini challenge: receipt helpers
Write four small methods that build the lines of a shop receipt. The methods must return their values, and only the script at the bottom is allowed to print.
- line_total(price, quantity = 1) returns price * quantity (no puts, no return keyword)
- bulk?(quantity) returns true when quantity is 10 or more
- receipt_line(name, price, quantity: 1) returns a string like "Tea x1 = 2.50" and appends " (bulk)" for bulk orders
- sum_lines(*totals) adds up however many amounts it receives
def line_total(price, quantity = 1)
# TODO: return price * quantity (no puts, no return keyword)
end
def bulk?(quantity)
# TODO: true when quantity is 10 or more
end
def receipt_line(name, price, quantity: 1)
# TODO: build "Tea x1 = 2.50" and add " (bulk)" for bulk orders
end
def sum_lines(*totals)
# TODO: add up any number of line totals
end
# TODO: print two receipt lines and then the grand totalExpected: Tea x1 = 2.50 Sugar x12 = 18.00 (bulk) Total: 20.50
Show hint
format("%.2f", amount) prints two decimal places, and a ternary (condition ? a : b) can decide whether to add " (bulk)". A splat parameter is an array, so totals.sum works.
Show solution
def line_total(price, quantity = 1)
price * quantity
end
def bulk?(quantity)
quantity >= 10
end
def receipt_line(name, price, quantity: 1)
text = format("%s x%d = %.2f", name, quantity, line_total(price, quantity))
bulk?(quantity) ? "#{text} (bulk)" : text
end
def sum_lines(*totals)
totals.sum
end
puts receipt_line("Tea", 2.5)
puts receipt_line("Sugar", 1.5, quantity: 12)
grand_total = sum_lines(line_total(2.5), line_total(1.5, 12))
puts "Total: #{format('%.2f', grand_total)}"Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A method returns the value of its last expression, so use return mainly for early exits.
- puts prints and returns nil; keep calculating methods free of puts.
- Use default values, keyword arguments (name: value) and splats (*args) for flexible calls; there is no overloading.
- A ? name should return true or false; a ! name is the more dangerous variant, but it is only a convention and may return nil.
Official Ruby Documentation — Ruby Documentation