Skip to content
Justice Tech School

Blocks, Yield and Procs

A block is code passed to a method. yield runs it, block_given? checks for it and &block captures it as a Proc. Lambdas are stricter procs.

Example
def twice
  return "no block" unless block_given?
  yield
  yield
end
twice { puts "hi" }
puts twice
add = ->(a, b) { a + b }
puts add.call(2, 3), add.(4, 5), add[1, 1]
sq = proc { |x| (x || 0) ** 2 }
puts sq.call(6)

Result

hi
hi
no block
5
9
2
36

Exercise

Run the block.

def m
  
end

Quiz Test

What does yield do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.