Methods in Ruby are defined with def and always return the last
expression. Ruby has unique features like blocks, procs and lambdas
that make it exceptionally expressive.
Basic Method
Ruby
def greet(name)
"Hello, #{name}!" # implicit return — no "return" keyword needed
end
puts greet("Sita") # "Hello, Sita!"Default and Keyword Arguments
Ruby
def create_user(name, age: 18, role: :student)
{ name: name, age: age, role: role }
end
create_user("Ram")
# => { name: "Ram", age: 18, role: :student }
create_user("Sita", age: 21, role: :admin)
# => { name: "Sita", age: 21, role: :admin }Blocks
A block is a chunk of code passed to a method:
Ruby
3.times do |i|
puts "Iteration #{i}"
end
[1, 2, 3].each { |n| puts n * 2 }yield
Call the block from inside the method:
Ruby
def with_timer
start = Time.now
yield # runs the block
elapsed = Time.now - start
puts "Done in #{elapsed.round(2)}s"
end
with_timer { sleep(1) } # "Done in 1.0s"Procs and Lambdas
Ruby
# Proc — loose syntax, no arity check
square = Proc.new { |n| n * n }
square.call(5) # 25
# Lambda — strict syntax, arity check
cube = lambda { |n| n ** 3 }
cube.call(3) # 27
# Shorthand
multiply = ->(a, b) { a * b }
multiply.(4, 5) # 20Each, Map, Select, Reduce
Ruby
nums = [1, 2, 3, 4, 5]
nums.each { |n| puts n } # iterate
doubled = nums.map { |n| n * 2 } # [2, 4, 6, 8, 10]
evens = nums.select { |n| n.even? } # [2, 4]
sum = nums.reduce(:+) # 15Tips
- Blocks are everywhere in Ruby — learn
each,map,select. - Use keyword arguments for methods with 3+ parameters.
- Implicit return — the last expression is automatically returned.
- Use symbols for method names and hash keys.
Next: classes — open classes and mixins.