All lessons

Methods

8 min · Ruby

Package code under a name so you can reuse it (Ruby calls them methods).

Ruby · Methods0/5 cleared

Enemy 1 of 5

Defining a method

In most languages this concept is called a "function," but Ruby calls it a method, because in Ruby literally everything — including plain numbers and strings — is an object, and a piece of reusable behavior attached to objects is conventionally called a method rather than a standalone function. You'll see both words used loosely in casual conversation, but "method" is the term you'll find throughout Ruby's own documentation.

The value of packaging logic into a method is the same regardless of what you call it: write the logic once, give it a name, and call that name instead of repeating the underlying steps every time you need them.

You define a method with def, a name, an optional parameter list in parentheses, and end to close it off — no curly braces, matching the same style you saw with if blocks. Parameters (like n in def double(n)) are placeholder names that receive whatever values are passed in when the method is called.

Ruby has a distinctive feature here: the value of the last evaluated expression in a method is automatically returned, even without an explicit return keyword. So def double(n); n * 2; end would work identically to using return n * 2. Using return explicitly (as the example does) is still common and often clearer, especially if you want to exit the method early, but it's genuinely optional for the final line.

Calling a method is as simple as writing its name followed by arguments — double(5) runs the method with n bound to 5, and the returned value (10) is what puts double(5) ends up printing.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10