Methods
A method is a named piece of code. Ruby methods are flexible: arguments can have defaults or names, the last expression is returned automatically, and calls look like plain English because parentheses are optional.
Defining methods
def name(params) … enddefines a method.- The last expression is returned automatically. You only write
returnto leave early. - Method names use
snake_case. Names ending in?return a boolean; names ending in!change the object or are "dangerous".
Arguments
Defaults
Keyword arguments
For anything with more than one or two options, use keyword arguments. They're self-documenting and can be given in any order:
name: with no default is required:
Any number of arguments
| Syntax | Collects |
|---|---|
*args |
Extra positional arguments, as an array |
**opts |
Extra keyword arguments, as a hash |
&block |
A block passed to the method (next-but-one lesson) |
Returning several values
Return an array and destructure it:
Scope
Methods can't see variables from outside them. Each method has its own local variables:
Pass what a method needs as arguments. (Blocks are different: they can see the variables around them, as you'll see later.)
Objects are passed by reference
Arguments are references to the same object. Calling a method that changes the object is visible outside; reassigning the parameter isn't:
Recursion
memo[n] ||= … computes a value only the first time and stores it (memoisation), which turns an exponentially slow function into a fast one.
Method objects and method_missing, briefly
Methods are objects you can pass around:
That flexibility is the base of Ruby's metaprogramming, covered in its own lesson.
Practice
- Write
def bmi(weight_kg, height_m)that returns the BMI rounded to 1 decimal. - Write
def format_price(cents, currency: "₹")that returns strings like₹19.99. - Write
def average(*numbers)that returns0when given no numbers. - Write
def palindrome?(text)that ignores case and spaces.
1.What does a Ruby method return if there's no return statement?
2.Which call matches def ship(order, express: false)?
3.Inside a method, can you use a local variable defined outside it?
4.What does def collect(*items) do with collect(1, 2, 3)?