Codectionary / Developer documentation / Ruby

Ruby Methods, Blocks & Enumerable

Methods are declared with def and return their final expression unless return is used explicitly. Many collection methods accept blocks, which makes transformations and filtering concise.

Syntax

def square(number)
  number * number
end

[1, 2, 3].map { |n| square(n) }

Examples

Transforming an array

A small, runnable example of this syntax.

def square(number)
  number * number
end

results = [1, 2, 3].map { |number| square(number) }
puts results.inspect  # [1, 4, 9]

Best practices

  • Choose descriptive block parameter names when a block has more than one step; the short form is best for genuinely simple transformations.
  • Keep examples small while learning, then combine the idea with a real project.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading