Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 134 ยท Methods and Blocks

Methods

Learn how to define and call Ruby methods - def, implicit return, multiple return values, predicate and bang naming, default arguments, scope and good method design.

A method is a named piece of code you can run whenever you want, with different inputs each time. Methods are how you avoid repeating yourself, how you give names to ideas ("calculate the tax", "is this a leap year?"), and how objects do anything at all: in Ruby, even 1 + 2 is a method call on the number 1.

This lesson covers defining and calling methods, what they return (Ruby has a slightly unusual answer), returning several values, the naming conventions with ? and !, how variables behave inside methods, and a few design guidelines. The next lesson, Method Arguments, goes deep on parameters.

Defining and calling a method

Ruby Your first methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

def starts a definition, followed by the name, a parameter list in parentheses, the body, and end. Method names use snake_case. To call a method, write its name with arguments. Parentheses on calls are optional (puts "hi" works), but Ruby programmers use them for methods that take arguments and are called for their value, and leave them out for DSL-style calls such as puts, require and attr_reader.

A method must be defined before the line that calls it runs. The next example shows what happens otherwise:

Ruby Calling an undefined method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program prints start, and then fails with main.rb:2:in '<main>': undefined method 'hello' for main (NoMethodError), followed by a snippet of the offending line. The definition on line 4 had not been executed yet when line 2 ran. Ruby defines methods when execution reaches the def, not at parse time. Move the def above the call, or put it in a file you require first.

The return value

Every Ruby method returns a value: the value of the last expression it evaluates. The keyword return is optional there.

Ruby Implicit and explicit return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Idiomatic Ruby omits return at the end of a method and uses it only for early exits: a guard clause at the top that handles edge cases and keeps the main logic flat. The last example is a classic trap: a method whose last line is puts returns nil, not the text. If you want both printing and a value, say so explicitly.

A method also returns nil if its body is empty or if an if without else is the last expression and the condition is false:

Ruby When a method returns nil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Returning more than one value

A method returns one object, but that object can be an array. Combined with multiple assignment, it feels like returning several values.

Ruby Returning multiple values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

For two or three values, an array is fine. When the pieces have names, a hash (or a Struct/Data, see Struct and Data) documents itself better: result[:average] is clearer than result[1].

Predicate and bang methods

Two naming conventions are used throughout the core library, and you should follow them in your own code.

  • A trailing ? marks a predicate, a method that answers a yes/no question and returns true or false (or at least something truthy/falsy): empty?, include?, nil?, even?.
  • A trailing ! marks a dangerous version of a method: usually it changes the receiver in place, or raises an error where the plain version returns nil.
Ruby Predicates and bang methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last two lines show why bang methods are "dangerous": upcase! returns nil when the string was already uppercase, so text = text.upcase! can turn a string into nil. Prefer the non-bang version unless you really need in-place change (for example, to save memory on a huge string). The bang is a convention, not a rule of the language: Ruby does not check it, so a method called save! only does what its author documented. In Rails, for instance, save! raises on failure while save returns false.

A method name may also end in =: that defines a setter, such as def name=(value), called with object.name = "x" (Classes and Objects).

Variables inside methods

A method body has its own local scope. It cannot see local variables of the code that calls it, and its own locals vanish when it returns.

Ruby Method scope (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This fails with main.rb:4:in 'Object#with_tax': undefined local variable or method 'rate' for main (NameError). rate is a local variable of the main script, and def starts a new scope that cannot see it. The solutions, in order of preference:

  1. pass it as an argument: def with_tax(price, rate);
  2. use a constant, RATE = 0.2, visible everywhere;
  3. use a block (blocks do see the surrounding locals, see Closures and Binding) or an instance variable inside a class.
Ruby Passing the value in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Methods on objects

The def at the top level of a script defines a private method on Object that is available everywhere. Inside a class, def defines a method for instances:

Ruby The same idea on an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Calling t.fahrenheit sends the message fahrenheit to the object. Operators are ordinary methods: 5 + 3 is 5.+(3), and send(:+, 3) is the same call written explicitly. The variable @celsius belongs to the object, so every method of the object can read it.

Method design guidelines

  • One job per method. If you struggle to name it without "and", split it.
  • Keep them short. Most Ruby methods fit in five to ten lines.
  • Name by intent: total_price, not calc. Use verbs for actions, nouns or adjectives for values and predicates.
  • Use guard clauses instead of deep nesting.
  • Avoid hidden side effects. A method called total should not print or change state.
  • Prefer returning values over printing, so the result can be tested and reused. Separate computing from displaying.
Ruby Compute, then print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

order_total only computes, receipt only builds text, and puts at the very end does the printing. Both helpers can be called from a test without capturing output.

A trailing hint about performance: a method call has a small cost, but it is rarely the bottleneck. Do not inline code to save a call; write clear methods first and measure (Performance Tips). For short single-expression methods, Ruby has the compact endless form def square(n) = n * n (Endless Methods).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this method return? def f; 1; 2; 3; end

    A method returns the value of its last evaluated expression, which is 3. The earlier values are evaluated and discarded.
  2. 2. What does a trailing ? in a method name like empty? conventionally mean?

    Predicate methods end in ? and return true or false (or a truthy/falsy value).
  3. 3. Why can text = text.upcase! be a bug?

    Many bang methods return nil if they made no change, so assigning the result can replace your string with nil.
  4. 4. Why does a method defined with def raise NameError when it reads a local variable rate from the surrounding script?

    def is a scope gate. Pass the value as an argument, or use a constant, instance variable or block.
  5. 5. How do you return two values from a method?

    A method returns one object; returning an array and writing low, high = min_max(list) gives the effect of several return values.

Summary

  • Define methods with def name(params) ... end; they must be defined before the call executes.
  • A method returns the value of its last expression; use return mainly for early exits (guard clauses). A method ending in puts returns nil.
  • Return several values as an array (unpack with multiple assignment) or as a hash/Struct/Data.
  • ? marks predicates, ! marks "dangerous" variants that often modify the receiver or return nil when nothing changed.
  • A method has its own local scope: pass values in as arguments instead of relying on outer locals.
  • Keep methods short, name them by intent, and separate computing from printing.

Next: Method Arguments