Methods in Ruby
Define and call methods, work with parameters, default values, keyword arguments, splat operators, and return values in Ruby.
Method Basics & Execution Flow
Methods are defined with `def` and ended with `end`. Ruby methods always return a value — the last evaluated expression is the implicit return.
1. Defining and Calling a Method
Use `def method_name` ... `end` to define a method. Call it by name.
2. Implicit Return
Ruby methods return the value of the last evaluated expression — no `return` keyword needed.
3. Execution Flow
Methods stop execution when `return` is hit or they reach the end.
Parameters & Arguments
Ruby methods support positional parameters, default values, keyword arguments, and splat operators.
1. Positional Parameters
Parameters are listed in the method definition and matched by position.
2. Default Parameter Values
Set a default value for a parameter — used when no argument is provided.
3. Keyword Arguments
Keyword arguments use `name:` syntax and can be passed in any order.
Unlimited Parameters (Splat)
Ruby uses `*args` for a variable-length list of positional arguments and `**kwargs` for a variable-length set of keyword arguments.
1. *args — Splat Operator
`*args` collects all extra positional arguments into an array.
2. **kwargs — Double Splat
`**kwargs` collects extra keyword arguments into a hash.
Method Forms
Ruby has conventions for method naming: predicate methods end with `?`, bang methods end with `!`, and setter methods end with `=`.
1. Predicate Methods (?)
Methods ending in `?` return a boolean — they ask a yes/no question.
2. Bang Methods (!)
Methods ending in `!` modify the object in place or raise an exception on failure.
3. Method Aliases
`alias` and `alias_method` create a new name for an existing method.
Closures & State
Ruby methods do not close over local variables, but Procs and lambdas do. A closure "remembers" the variables from the scope where it was created.
1. Proc as a Closure
A `Proc` captures the local variables of its surrounding scope.
2. Lambda
Lambdas are like Procs but enforce argument count and have their own return scope.
Higher-Order Methods
Ruby methods can accept blocks with `yield`, accept Procs/lambdas as arguments, and return Procs/lambdas.
1. yield — Accepting a Block
`yield` calls the block passed to a method.
2. Passing a Proc as an Argument
Use `&` to convert a Proc/lambda to a block or receive a block as a Proc.
3. Method Returning a Lambda
Methods can return lambdas to create reusable function factories.