Blocks, Procs, and Lambdas

Ruby supports functional programming using blocks, Procs, and lambdas.

Blocks:

Blocks are anonymous chunks of code passed to methods.

def greet
  yield
end

greet { puts "Hello from a block" }

Procs:

say_hi = Proc.new { puts "Hi" }
say_hi.call

Lambdas:

add = lambda { |a, b| a + b }
puts add.call(2, 3)

Lambdas are stricter with arguments than Procs.

← PrevNext →