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.

At a glance

Purpose
Expressive scripting and applications
File extension
.rb
Runs in
Ruby interpreter
Usually used with
Ruby standard library and gems

Specifications & further reading

Related Ruby documentation