Methods

Lesson 6 of 20

Wrap code into reusable methods with def, pass in parameters and let the last expression fly back out.

The big picture

Name a chunk of code

A method is a named, reusable chunk of code: define it once with def, call it as many times as you like.

def names it

def greet ... end stores the code under a name — nothing runs until you call it.

Parameters catch input

Names between the parentheses catch the arguments you pass in at call time.

Last line returns

No return keyword needed — the final expression of the body is the result.

Parentheses optional

greet("Ada") and greet "Ada" both work — Ruby style prefers ( ) on methods with arguments.