Methods
Define methods with the def keyword. Give them a name and you're off:
def greet
"Hello, world!"
end
greet # => "Hello, world!"
Parameters can have default values. If the caller doesn't pass anything, the default kicks in:
def greet(name = "stranger")
"Hello, #{name}!"
end
greet("Alice") # => "Hello, Alice!"
greet # => "Hello, stranger!"
Splat arguments let you accept any number of arguments as an array:
def sum(*numbers)
numbers.reduce(0, :+)
end
sum(1, 2, 3) # => 6
sum(10, 20, 30) # => 60
Keyword arguments make your method calls self-documenting. The caller knows exactly what each value means:
def create_user(name:, age:, role: "viewer")
"#{name}, #{age}, #{role}"
end
create_user(name: "Alice", age: 30, role: "admin")
Ruby returns the value of the last expression automatically. Use return only when you need to exit early:
def classify(number)
return "zero" if number == 0
number > 0 ? "positive" : "negative"
end
You can alias a method with alias to give it a second name:
def say_hello
"hello"
end
alias greeting say_hello
greeting # => "hello"
Remember: in Ruby, methods are just messages you send to objects. When you call 42.odd?, you're sending the odd? message to the integer 42. That's the whole philosophy.