Blocks

View saved

Blocks with each

A block is code attached to a method call.

[1, 2, 3].each do |n|
  puts n * 2
end

Brace form

Braces are common for one-liners.

squares = [1, 2, 3].map { |n| n * n }
puts squares.inspect

Yield inside your method

A method can call a provided block with yield.

def twice
  yield
  yield
end

twice { puts "hi" }

Block tips

  • do/end for multi-line; {} for single-line is a common style
  • |params| receive block arguments
  • Blocks are not the same as methods, but Proc/lambda exist for later
  • Many Ruby APIs expect a block

Comments

One comment per signed-in account. Comments are saved with this page’s URL.