%q{Blocks}
# Single line block (1..2).map { |x| x * 2} => [2, 4]
# Multi-line block (1..2).map do |x| x * 2 end => [2, 4]
# Calling a block def foo(&block) block.call end
# Or like this def foo yield end
# Calling block with params def bar(&block) block.call(1, 2) end
# Or like this def bar yield(1,2) end
# Yield many times def baz yield(1,2) yield(2,4) end
# Default arguments foo {|x=0, y=1| x+y}
# Keyword arguments bar {|x:, y:| x+y}
# Blocks are procs in disguise def block_class(&block) block.class end
block_class { } => Proc
| %q{Procs}
# Define a proc p = Proc.new {|x,y| x+y}
# Or like this p = proc { |x, y| x + y}
# Multi-line proc p = proc do |x, y| x + y end
# Calling a proc p.call(1, 2) p.(1, 2) p[1, 2] p.[1, 2]
# Passing proc as block def foo(&block) block end foo(&p) => #<Proc::0x0055de...>
# Procs ignore param count p = proc { |x| x+1 }
p.call(1) => 2
p.call(1,2) => 2
# Proc return behaviour def proc_return p = proc { return } puts 'Hello' p.call puts 'World' end
proc_return # Hello
# Convert symbol to proc p = :even?.to_proc
p.call(1) => false
p.call(2) => true
| %q{Lambdas}
# Define a lambda l = lambda {|x,y| x+y}
# Or "stabby" lambda syntax l = -> { 'hello world' } l = ->(x,y) { x + y }
# Brackets are optional l = -> x,y { x + y }
# Calling a lambda l.call(1, 2) l.(1, 2) l[1, 2] l.[1, 2]
# Passing lambda as block def foo(&block) block end foo(&l) => #<Proc::0x0055de... (lambda)>
# Lambdas check parameter count l = lambda { |x| x+1 }
l.call(1) => 2
l.call(1, 2) => ArgumentError
# Lambda return behaviour def lambda_return l = lambda { return } puts 'Hello' l.call puts 'World' end
lambda_return # Hello # World
|