Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 12 of 23 · Ruby 3.2

Name reusable work

Define a method with arguments and use its returned value.

Learn

Define a method with def, a name, optional parameters in parentheses, a body and end. Calling the method runs the body. Arguments supplied at the call fill the corresponding parameters.

A method returns the value of the last expression it evaluates. Assign that value or pass it to another method such as puts. Printing inside a method and returning a value are separate actions.

Use return value to finish a method early. A parameter may have a default, such as quantity = 1, which is used when that argument is omitted. Local variables created inside a method stay local to that call.

Example

def item_total(price, quantity)
  price * quantity
end

total = item_total(6, 3)
puts total

Experiment

  • Predict both totals. Add a third call for 5 items priced at 4 each without changing the definition.

  • Predict the two prices. Change the default quantity to 2 and identify which call is affected.

  • Predict both labels. Change the invalid quantity to 1 and trace which return path runs.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.