liveBook · Manning

Last expression

As explained in The Well-Grounded Rubyist, Fourth Edition

The last expression is the final expression evaluated in a Ruby method body, whose value becomes the method's implicit return value unless an explicit return intervenes.

Ruby treats every method body as a sequence of expressions. The method’s return value is the value produced by the last expression evaluated, so an explicit return is often unnecessary. For example, a temperature-conversion calculation can be the method’s only expression and becomes its result. section 2.1.4

A getter returns its instance variable

def venue @venue end The expression @venue is the final—and only—expression in venue, so calling venue returns the stored venue. An explicit return can make the result more visible, return from the middle of a method, or return multiple values; an empty method body returns nil. section 3.2.1 section 2.1.4

Table 2.1 Examples of Ruby expressions and the values to which they evaluate

Expression

Value

Comments

2 + 2

4

Arithmetic expressions evaluate to their results.

"Hello"

"Hello"

A simple, literal string (in quotation marks) evaluates to itself.

"Hello" + " there"

"Hello there"

Strings can be “added” to each other (concatenated) with the plus sign.

c = 100

100

When you assign to a variable, the whole assignment evaluates to the value you’ve assigned.

c * 9/5 + 32

212

The usual rules of precedence apply: multiplication and division bind more tightly than addition and are performed first.

obj.c2f(100)

212

A method call is an expression.

Use the expression table to compare arithmetic, literals, assignments, and method calls: each evaluates to a value that can become a later expression’s input or a method’s result. section 2.1.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the last-expression rule through methods, getters, empty bodies, multiple values, and class-definition blocks, without covering evaluation internals.
Examples
Uses temperature conversion, ticket getters, class-definition blocks, IRB evaluations, and stored instance variables as concrete cases.
What it assumes
Assumes basic Ruby methods, method calls, expressions, and instance variables while establishing that every expression evaluates to a value.
What you can do after
Evaluate Ruby methods by identifying their final expression and choose explicit return when control flow or multiple-value syntax requires it.
How it connects
Connects expressions with method return values, explicit return, instance variables, nil, truth values, and IRB’s last-expression variable.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.