Lesson 4 of 11
Methods
Learn how to define with ``, pass , and use blocks, procs and . A Ruby method returns the value of its last expression automatically.
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 . A trailing ! means the method is destructive (modifies the receiver in place).
# 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)# 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
endFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.