Block (Ruby)

A block is a chunk of code passed to a method, written with do...end or curly braces { }. Blocks are central to Ruby — they power iteration, resource handling, and most of the Enumerable methods.

Ruby

A block is an anonymous piece of code attached to a method call. The method can run it (often multiple times) using yield or by capturing it as a parameter. Blocks take arguments between pipes: [1,2,3].each { |n| puts n }.

Convention is to use { } for short, single-line blocks and do...end for multi-line ones. Only one block can be passed per method call (unlike procs/lambdas, which are objects you can pass around freely and store in variables).

Blocks make Ruby code read declaratively: each, map, select, times, and File.open all take blocks. The open/yield/close pattern (e.g. File.open with a block) also guarantees cleanup, since the method runs your block and then tidies up.

Syntax

method { |arg| ... }
method do |arg|
  ...
end

Examples

Ruby

3.times { |i| print i }
puts
[1, 2, 3].each do |n|
  print n * 2
end

Output:

012
246

Learn it in a lesson

See also

Back to the Dictionary