Ruby Blocks and Procs

Working with blocks, procs, and lambdas

Basic Blocks

# Block with do...end
[1, 2, 3].each do |num| # iterate with block
  puts num # print each number
end
# Block with curly braces
[1, 2, 3].each { |num| puts num } # inline block

Yield

def my_method # define method
  puts "Start"
  yield # execute block
  puts "End"
end
my_method { puts "Middle" } # call with block

Proc Objects

my_proc = Proc.new { |x| puts x * 2 } # create proc
my_proc.call(5) # execute proc (prints 10)
my_proc[5] # alternative syntax

Lambda

my_lambda = lambda { |x| x * 2 } # create lambda
my_lambda = ->(x) { x * 2 } # stabby lambda syntax
result = my_lambda.call(5) # execute lambda (returns 10)

Block Parameters

def method(&block) # accept block as parameter
  block.call if block # execute if block given
end
method { puts "Hello" } # pass block