RbRuby · Lesson 4 of 11

Methods

In Ruby, methods are defined with `def`. They implicitly return the last expression, which either feels elegant or terrifying — but saves a lot of typing.

Methods in Ruby don't need explicit return statements — the value of the last expression is automatically returned. A trailing ? means the method returns a boolean. A trailing ! means the method is destructive (modifies the receiver in place).

Ruby
# Basic method
def greet(name)
  "Hello, #{name}!"   # implicit return
end

puts greet("Alice")   # Hello, Alice!

# Default parameters
def greet_with_title(name, title: "Dr.")
  "Hello, #{title} #{name}!"
end

puts greet_with_title("Smith")              # Hello, Dr. Smith!
puts greet_with_title("Jones", title: "Prof.")  # Hello, Prof. Jones!

# ? methods return booleans
def adult?(age)
  age >= 18
end

puts adult?(20)  # true
puts adult?(15)  # false

# Splat — variable number of arguments
def sum(*numbers)
  numbers.sum
end

puts sum(1, 2, 3, 4, 5)   # 15

# Keyword arguments with **
def describe(**opts)
  opts.each { |k, v| puts "#{k}: #{v}" }
end

describe(name: "Alice", city: "Paris", age: 30)
Ruby
# Procs and Lambdas — anonymous functions
# Proc
square = Proc.new { |x| x ** 2 }
puts square.call(5)   # 25
puts square.(5)       # same, shorter syntax

# Lambda — stricter than Proc (checks argument count, different return behavior)
double = lambda { |x| x * 2 }
triple = ->(x) { x * 3 }   # stabby lambda syntax

puts double.call(4)  # 8
puts triple.(4)      # 12

# Method objects — convert a named method to a callable
puts [1, 2, 3].map(&method(:puts))  # prints 1, 2, 3

# yield — call the block passed to a method
def repeat(n)
  n.times { yield }
end

repeat(3) { print "hi " }   # hi hi hi

# block_given? — check if a block was passed
def optionally_fancy(name)
  if block_given?
    yield name
  else
    "Hello, #{name}"
  end
end
✦ Tip
The difference between Proc and Lambda: lambdas check argument count and `return` exits only the lambda. Procs are loose about arguments and `return` exits the enclosing method. In most cases, prefer lambdas (`->`) for anonymous functions you pass around.