Endless method definitions
suggest changeMany Ruby methods are a single expression wrapped in three lines of ceremony:
def area
width * height
end
Ruby 3.0 added a shorter form, the endless method definition, where = takes the place of the body and the end:
def area = width * height
Both forms define the same method. Ruby 3.1 extended the syntax so the body can be a command call without parentheses (def hello = puts "Hello").
This article covers the syntax rules, what can and can't be defined this way, the precedence traps around rescue, and and if, how endless methods combine with private and other decorators, and RuboCop's cops for them. All examples were run with Ruby 4.0 and RuboCop 1.92. For regular def syntax see Defining a method.
The basics
An endless method is def, the name, an optional parameter list in parentheses, = and one expression. The value of the expression is the return value:
class Rect
attr_reader :width, :height
def initialize(width, height) = (@width, @height = width, height)
def area = width * height
def perimeter = 2 * (width + height)
def square? = width == height
def scale(factor) = Rect.new(width * factor, height * factor)
def to_s = "#{width}x#{height}"
def ==(other) = other.is_a?(Rect) && width == other.width && height == other.height
def self.square(side) = new(side, side)
end
r = Rect.new(3, 4)
puts r.area
puts r.perimeter
p r.square?
puts r.scale(2)
p Rect.square(5).square?
p r == Rect.new(3, 4)
12
14
false
6x8
true
true
Predicates (square?), bang methods, operators (==), class methods (def self.square) and initialize can all be written this way. The parentheses around the multiple assignment in initialize are needed because a, b = x, y on its own isn't a single expression.
Parameters
Any parameter list works: required, optional, splat, keyword, block and forwarding parameters.
def greet(name = "world", punct: "!") = "Hello, #{name}#{punct}"
p greet
p greet("Ruby", punct: "?")
"Hello, world!"
"Hello, Ruby?"
The parentheses around the parameters are required. Without them Ruby reads the = as a default value of the last parameter, and then waits for a regular body and an end:
def add a, b = a + b
no_parens.rb: no_parens.rb:1: syntax errors found (SyntaxError)
> 1 | def add a, b = a + b
| ^~~ expected an `end` to close the `def` statement
| ^ unexpected end-of-input, assuming it is closing the parent top level context
So this line starts an ordinary method add(a, b = a + b), not an endless one.
For a method without parameters, put a space before =. Without the space, answer= is read as the name of a setter method:
def answer=42
no_space.rb: no_space.rb:1: syntax errors found (SyntaxError)
> 1 | def answer=42
| ^~~ expected an `end` to close the `def` statement
| ^ expected a delimiter to close the parameters
| ^ unexpected end-of-input, assuming it is closing the parent top level context
def answer = 42 and def answer()=42 both work. Always write spaces around =.
Setters can't be endless
A method whose name ends in = can't be defined in endless form. def name=(value) = @name = value would be very hard to read, so Ruby rejects it:
class Person
def name=(value) = @name = value
end
setter.rb: setter.rb:2: syntax error found (SyntaxError)
1 | class Person
> 2 | def name=(value) = @name = value
| ^~~~~ invalid method name; a setter method cannot be defined in an endless method definition
3 | end
The same applies to []=. Use attr_writer/attr_accessor or a regular def for setters. Other operators (+, -@, [], <=>, ==) are fine:
class Vec
include Comparable
attr_reader :x, :y
def initialize(x, y) = (@x, @y = x, y)
def +(other) = Vec.new(x + other.x, y + other.y)
def -@ = Vec.new(-x, -y)
def [](i) = [x, y].fetch(i)
def <=>(other) = length <=> other.length
def length = Math.hypot(x, y)
def to_s = "(#{x}, #{y})"
end
a = Vec.new(1, 2)
b = Vec.new(3, 4)
puts a + b
puts(-a)
p b[1]
p a < b
p [b, a].max.to_s
(4, 6)
(-1, -2)
4
true
"(3, 4)"
Assignments inside the body are allowed, as long as the method itself isn't a setter. Lazy initialization with ||= is a common one-liner:
class Cart
def items = @items ||= []
def add(item) = items << item
end
c = Cart.new
c.add("pen")
c.add("ink")
p c.items
["pen", "ink"]
Command calls as the body (Ruby 3.1+)
In Ruby 3.0 the body had to be an "argument-like" expression, so def hello = puts "Hello" was a syntax error and you had to write puts("Hello"). Since 3.1, a method call without parentheses works as the body:
def hello = puts "Hello"
def greet(name) = puts "Hello, #{name}"
def log(msg) = warn "[log] #{msg}"
hello
greet "Ruby"
p hello
Hello
Hello, Ruby
Hello
nil
p hello prints Hello from the method and then nil, which is what puts returns.
Blocks, heredocs and longer bodies
The body can contain blocks, both { } and do ... end, and you can pass blocks through:
class Inventory
def initialize(items) = @items = items
def total = @items.sum { it[:price] * it[:qty] }
def names = @items.map { it[:name] }.sort
def in_stock = @items.select do
it[:qty] > 0
end
def each_name(&) = names.each(&)
def twice = [yield, yield]
end
inv = Inventory.new([
{name: "pen", price: 2, qty: 10},
{name: "ink", price: 5, qty: 0},
{name: "pad", price: 3, qty: 4}
])
p inv.total
p inv.names
p inv.in_stock.map { it[:name] }
inv.each_name { puts it }
n = 0
p inv.twice { n += 1 }
32
["ink", "pad", "pen"]
["pen", "pad"]
ink
pad
pen
[1, 2]
it is the implicit block parameter from Ruby 3.4, see Block parameters: it and numbered parameters. def each_name(&) = names.each(&) uses an anonymous block parameter (Ruby 3.1) to forward the block.
The body is one expression, but that expression may span lines. A heredoc is a single expression too:
def summary(user) =
"#{user[:name]} (#{user[:email]}), " \
"member since #{user[:joined]}"
def usage = <<~TXT
Usage: tool [options] FILE
-v verbose
TXT
puts summary(name: "Ann", email: "ann@example.com", joined: 2019)
puts usage
Ann (ann@example.com), member since 2019
Usage: tool [options] FILE
-v verbose
You can even fit several statements in with parentheses or begin ... end:
def stats(nums) = (
total = nums.sum
avg = total.fdiv(nums.size)
{ total:, avg: }
)
def stats2(nums) = begin
total = nums.sum
{ total:, avg: total.fdiv(nums.size) }
end
p stats([1, 2, 3, 4])
p stats2([1, 2, 3, 4])
{total: 10, avg: 2.5}
{total: 10, avg: 2.5}
That this works doesn't mean you should do it. def stats2(nums) = begin ... end is longer than a normal method and harder to scan. Once the body needs more than one line, a regular def is usually clearer.
Note that a semicolon ends the definition. In def one = 1; two = 2 the second assignment is a separate statement, not part of the method body:
def one = 1; two = 2
p one
p two
1
2
Precedence pitfalls
The body of an endless method extends as far as a normal expression would, with three cases worth knowing.
rescue modifier: part of the body
A trailing rescue modifier belongs to the body, which is usually what you want:
def parse(s) = Integer(s) rescue 0
p parse("42")
p parse("abc")
42
0
A rescue clause on its own line isn't allowed, because there is no end for it to belong to:
def foo = 1
rescue
2
rescue_clause.rb: rescue_clause.rb:2: syntax error found (SyntaxError)
1 | def foo = 1
> 2 | rescue
| ^~~~~~ unexpected 'rescue', ignoring it
3 | 2
The same is true for ensure. If you need either, use a regular method.
and, or: outside the body
and and or have lower precedence than the definition itself, so they apply to the def expression, not to the body:
def check = puts("first") and puts("second")
puts "--- calling check"
check
second
--- calling check
first
This parses as (def check = puts("first")) and puts("second"). A def returns the method name as a symbol (see Method Definitions are Expressions), :check is truthy, and so puts("second") runs once, when the file is loaded. The method only prints first. Use && and || in endless bodies, or wrap the body in parentheses.
if and unless modifiers: around the whole definition
A trailing if or unless makes the definition conditional, not the body:
def maybe = 42 if false
p respond_to?(:maybe, true)
def flag = true if true
p flag
false
true
maybe was never defined. This can be used on purpose (define a method only on some platforms), but if you wanted a method that returns nil when a condition is false, write def maybe = (42 if cond) or use a ternary.
private def and other decorators
def returns the method's name, so endless methods work with anything that takes a method name, such as private, protected, module_function or your own decorators:
class Account
def initialize(balance) = @balance = balance
def report = "Balance: #{format_money(@balance)}"
private def format_money(cents) = format("$%.2f", cents / 100.0)
private def shout = puts "loud"
end
a = Account.new(12345)
puts a.report
begin
a.format_money(1)
rescue NoMethodError => e
puts e.message
end
p Account.private_instance_methods(false)
Balance: $123.45
private method 'format_money' called for an instance of Account
[:shout, :format_money, :initialize]
private def shout = puts "loud" combines a command-call body with private. Ruby 4.0 accepts it with both the default Prism parser and --parser=parse.y.
The same trick works with a memoizing decorator:
module Memoize
def memoize(name)
impl = instance_method(name)
define_method(name) do
@memo ||= {}
@memo.fetch(name) { @memo[name] = impl.bind_call(self) }
end
name
end
end
class Report
extend Memoize
memoize def data = (puts "loading..."; [3, 1, 2])
memoize def sorted = data.sort
end
r = Report.new
p r.sorted
p r.sorted
p r.data
loading...
[1, 2, 3]
[1, 2, 3]
[3, 1, 2]
Where endless methods fit well
Small value objects and utility modules are full of one-expression methods, which makes them a natural fit:
Point = Data.define(:x, :y) do
def self.origin = new(x: 0, y: 0)
def +(other) = with(x: x + other.x, y: y + other.y)
def distance_to(other) = Math.hypot(x - other.x, y - other.y)
def to_s = "(#{x}, #{y})"
end
module Temperature
module_function
def c_to_f(c) = c * 9.0 / 5 + 32
def f_to_c(f) = (f - 32) * 5 / 9.0
end
a = Point.new(x: 3, y: 4)
puts a + Point.new(x: 1, y: 1)
p a.distance_to(Point.origin)
p Temperature.c_to_f(100)
p Temperature.f_to_c(212)
obj = Object.new
def obj.greeting = "hi from a singleton"
p obj.greeting
(4, 5)
5.0
212.0
100.0
"hi from a singleton"
See Immutable value objects with Data for more on Data.define. The last lines show that singleton methods (def obj.greeting) can be endless too.
Good candidates:
- computed attributes and predicates:
def full_name = "#{first} #{last}",def empty? = size.zero? - operators and conversions:
def <=>(other) = ...,def to_s = ...,def to_h = ... - simple delegation:
def size = @items.size - factory class methods:
def self.origin = new(0, 0)
Use a regular def when the method has several statements, needs rescue/ensure clauses, is a setter, or doesn't fit comfortably on one line.
RuboCop
Two RuboCop cops deal with endless methods. Both are "pending", so they run when NewCops: enable is set in .rubocop.yml (or you enable them one by one).
Style/EndlessMethod controls when the syntax may be used. The default style is allow_single_line, which flags endless methods that span several lines:
# frozen_string_literal: true
# A circle.
class Circle
def initialize(radius) = @radius = radius
def area = Math::PI * @radius**2
def describe = format(
"circle r=%<r>s area=%<a>.2f",
r: @radius, a: area
)
def diameter
@radius * 2
end
end
$ rubocop --only Style/EndlessMethod shapes.rb
Inspecting 1 file
C
Offenses:
shapes.rb:9:3: C: [Correctable] Style/EndlessMethod: Avoid endless method definitions with multiple lines.
def describe = format( ...
^^^^^^^^^^^^^^^^^^^^^^
1 file inspected, 1 offense detected, 1 offense autocorrectable
The other supported styles are allow_always, disallow (no endless methods at all), require_single_line and require_always. With require_single_line, RuboCop also flags diameter, and rubocop -A converts it to def diameter = @radius * 2 while turning describe back into a regular method:
Style/EndlessMethod:
EnforcedStyle: require_single_line
shapes.rb:9:3: C: [Correctable] Style/EndlessMethod: Avoid endless method definitions with multiple lines.
def describe = format( ...
^^^^^^^^^^^^^^^^^^^^^^
shapes.rb:14:3: C: [Correctable] Style/EndlessMethod: Use endless method definitions for single line methods.
def diameter ...
^^^^^^^^^^^^
Style/AmbiguousEndlessMethodDefinition catches the and/or/if trap from above:
$ rubocop --only Style/AmbiguousEndlessMethodDefinition amb.rb
amb.rb:3:1: C: [Correctable] Style/AmbiguousEndlessMethodDefinition: Avoid using and statements with endless methods.
def check = puts('first') and puts('second')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Its autocorrection keeps the current meaning and makes it visible, rather than guessing what you meant:
def check
puts('first')
end and puts('second')
If you meant both calls to be part of the method, fix it by hand: def check = puts("first") && puts("second") won't work either, since puts returns nil, so use a regular method with two lines.
The community style guide, and Coding conventions, recommend the same rule as the default: endless methods for short, single-line, single-expression methods only.
Summary
| Rule | Example |
|---|---|
| Available since | Ruby 3.0; command-call bodies since 3.1 |
| Parameters need parentheses | def add(a, b) = a + b |
Space before = without parameters |
def answer = 42 |
No setters (name=, []=) |
use attr_writer or a regular def |
Trailing rescue belongs to the body |
def parse(s) = Integer(s) rescue 0 |
and/or/if apply to the whole def |
use && or parentheses around the body |
No rescue/ensure clauses |
use a regular def |
| Returns the method name | private def helper = ... |