Ruby Snippet

Blocks, Procs, and Lambdas

Difficulty: Medium

Ruby has three closely related callable forms: blocks (one-shot, attached to a method call), `Proc` objects (named, non-strict about arity), and `Lambda` objects (named, strict about arity and `return` semantics). This snippet shows how each is constructed, when `yield` versus `&block` is appropriate, and the subtle differences in `return` and arity checking that decide which to use.

Code Snippets
/

Blocks, Procs, and Lambdas

Blocks, Procs, and Lambdas

Ruby has three closely related callable forms: blocks (one-shot, attached to a method call), `Proc` objects (named, non-strict about arity), and `Lambda` objects (named, strict about arity and `return` semantics). This snippet shows how each is constructed, when `yield` versus `&block` is appropriate, and the subtle differences in `return` and arity checking that decide which to use.

Ruby
Medium
3 snippets
ruby-blocks
ruby-yield
ruby-procs-lambdas
functional-programming

799 views

4

Every Ruby method can implicitly accept ONE block; you do not declare it in the parameter list. Inside the method body, yield value calls the block with value; block_given? lets you behave differently when the caller did not pass one. Returning enum_for(:method_name, ...) when there is no block is the canonical pattern: it lets callers either consume the iterator inline OR get back an Enumerator they can chain with .lazy.map.first(...). This is exactly how built-in methods like Array#map behave.