A Quick Look at Ruby blocks, procs, and lambdas

Blocks, Procs, Lambdas

Blocks

def print_once
yield
end
print_once { puts “I ran.” }# => “I ran.”def print_twice
yield
yield
end
print_twice { puts “I ran.” }# => “I ran.”# => “I ran.”
def explicit_block(&block)
block.call #same as yield
end
explicit_block { puts “I’m an explicit block!” }# => “I’m an explicit block!”

Lambdas

greeting = -> { puts “Hello from a lambda!” }
greeting = lambda { puts “Hello from a lambda!” }
greeting = -> { puts “Hello from a lambda!” }greeting.call# => “Hello from a lambda!”
greeting = ->(name) { puts “Hello, #{name}” }greeting.call(“Lebowski”)# => “Hello, Lebowski”

Procs

greeting = Proc.new { ‘Hello!’ }greeting.call# => ‘Hello!’
greeting = Proc.new { |name| “Hello, #{name}!” }hello.call( “Lebowski” )# => “Hello, Lebowski!”

Full Stack Software Engineer | Audiophile