Cover by Michael Fitzgerald

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Methods

Methods provide a way to gather code (statements and expressions) into one place so that you can use it conveniently and, if necessary, repeatedly. You can define methods to do all kinds of things. In fact, most of the math operators in Ruby are actually methods.

Tip

This is the most concentrated discussion on methods that you'll find in this book, so you may find yourself coming back to this section after you have read further.

Here is a simple definition for a method named hello, created with the keywords def and end:

def hello
  puts "Hello, Matz!"
end

hello # => Hello, Matz!

The hello method simply outputs a string with puts. On the flip side, you can undefine a method with undef.

undef hello # undefines the method named hello

hello # try calling this method now
NameError: undefined local variable or method 'hello' for main:Object
        from (irb):11
        from :0

You can also define methods that have arguments, as shown here in the repeat method:

def repeat( word, times )
 puts word * times
end

repeat("Hello! ", 3) # => Hello! Hello! Hello!
repeat "Good-bye! ", 4 # => Good-bye! Good-bye! Good-bye! Good-bye!

The repeat method has two arguments, word and times. You can call a method that has arguments with or without parentheses around the arguments. You can even define method arguments without parentheses, but I don't usually do it that way.

Because you don't have to use parentheses, it is possible to have normal-looking math equations when you use operator methods, such as +. Each line that ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required