RbRuby
IntermediateLesson 7 of 16

Blocks, Procs & Lambdas – Ruby

The heart of Ruby: passing code as an argument, yield and closures.

A block is a piece of code that you pass to a method. The method calls it with yield. This is how each, map, File.open and countless other methods work – and you can build your own.

def dreimal
  yield 1
  yield 2
  yield 3
end
dreimal { |n| puts "Call #{n}" }

def mit_log(name)
  puts "-> #{name} starting"
  ergebnis = yield
  puts "<- #{name} done: #{ergebnis}"
  ergebnis
end
mit_log("Calculation") { 6 * 7 }

def optional
  return "no block" unless block_given?
  yield
end
puts optional
puts optional { "with block" }

Blocks are not objects, but you can store and pass them on as a Proc or lambda. & converts between block and Proc; &:symbol is a shorthand for "call this method".

quadrat = ->(x) { x * x }        # lambda
puts quadrat.call(4), quadrat.(5), quadrat[6]    # 16, 25, 36

puts [1, 2, 3].map(&quadrat).inspect             # [1, 4, 9]
puts %w[a b].map(&:upcase).inspect               # ["A", "B"]

def wende_an(liste, &block)
  liste.map(&block)
end
puts wende_an([1, 2]) { |x| x + 10 }.inspect     # [11, 12]

Blocks, Procs and lambdas are closures: they remember the variables of their surroundings.

def zaehler
  n = 0
  -> { n += 1 }
end

z = zaehler
z.call
z.call
puts z.call        # 3

Difference between lambda and Proc: a lambda checks the number of arguments like a method, a Proc is generous (missing arguments become nil).

l = ->(a, b) { a + b }
pr = proc { |a, b| "#{a.inspect} #{b.inspect}" }
puts pr.call(1)            # 1 nil
puts pr.call(1, 2, 3)      # 1 2
begin
  l.call(1)
rescue ArgumentError => e
  puts "Lambda: #{e.class}"    # ArgumentError
end
TipA lambda with return only exits the lambda itself, a Proc/block with return exits the enclosing method. This is rarely what you want – use next in blocks.