# Programming Ruby ### The Pragmatic Programmer's Guide
Previous < | Contents ^ | Next >

# More About Methods

Other languages have functions, procedures, methods, or routines, but in Ruby there is only the method---a chunk of expressions that return a value.

So far in this book, we've been defining and using methods without much thought. Now it's time to get into the details.

## Defining a Method

As we've seen throughout this book, a method is defined using the keyword `def`. Method names should begin with a lowercase letter.[You won't get an immediate error if you use an uppercase letter, but when Ruby sees you calling the method, it will first guess that it is a constant, not a method invocation, and as a result it may parse the call incorrectly.] Methods that act as queries are often named with a trailing ```?`'', such as `instance_of?`. Methods that are ``dangerous,'' or modify the receiver, might be named with a trailing ```!`''. For instance, `String` provides both a `chop` and a `chop!`. The first one returns a modified string; the second modifies the receiver in place. ```?`'' and ```!`'' are the only weird characters allowed as method name suffixes.

Now that we've specified a name for our new method, we may need to declare some parameters. These are simply a list of local variable names in parentheses. Some sample method declarations are

    def myNewMethod(arg1, arg2, arg3)     # 3 arguments
      # Code for the method would go here
    end

    def myOtherNewMethod                  # No arguments
      # Code for the method would go here
    end

Ruby lets you specify default values for a method's arguments---values that will be used if the caller doesn't pass them explicitly. This is done using the assignment operator.

`def coolDude(arg1="Miles", arg2="Coltrane", arg3="Roach")`
`"#{arg1}, #{arg2}, #{arg3}."`
`end`
``
`coolDude` | » | `"Miles, Coltrane, Roach."`
`coolDude("Bart")` | » | `"Bart, Coltrane, Roach."`
`coolDude("Bart", "Elwood")` | » | `"Bart, Elwood, Roach."`
`coolDude("Bart", "Elwood", "Linus")` | » | `"Bart, Elwood, Linus."`

The body of a method contains normal Ruby expressions, except that you may not define an instance method, class, or module within a method. The return value of a method is the value of the last expression executed, or the result of an explicit `return` expression.

### Variable-Length Argument Lists

But what if you want to pass in a variable number of arguments, or want to capture multiple arguments into a single parameter? Placing an asterisk before the name of the parameter after the ``normal'' parameters does just that.

`def varargs(arg1, *rest)`
`"Got #{arg1} and #{rest.join(', ')}"`
`end`
``
`varargs("one")` | » | `"Got one and "`
`varargs("one", "two")` | » | `"Got one and two"`
`varargs "one", "two", "three"` | » | `"Got one and two, three"`

In this example, the first argument is assigned to the first method parameter as usual. However, the next parameter is prefixed with an asterisk, so all the remaining arguments are bundled into a new `Array`, which is then assigned to that parameter.

### Methods and Blocks

As we discussed in the section on blocks and iterators beginning on page 38, when a method is called, it may be associated with a block. Normally, you simply call the block from within the method using `yield`.

    def takeBlock(p1)
      if block_given?
        yield(p1)
      else
        p1
      end
    end

`takeBlock("no block")` | » | `"no block"`
`takeBlock("no block") { |s| s.sub(/no /, '') }` | » | `"block"`

However, if the last parameter in a method definition is prefixed with an ampersand, any associated block is converted to a `Proc` object, and that object is assigned to the parameter.

`class TaxCalculator`
`def initialize(name, &block)`
`@name, @block = name, block`
`end`
`def getTax(amount)`
`"#@name on #{amount} = #{ @block.call(amount) }"`
`end`
`end`
``
`tc = TaxCalculator.new("Sales tax") { |amt| amt * 0.075 }`
``
`tc.getTax(100)` | » | `"Sales tax on 100 = 7.5"`
`tc.getTax(250)` | » | `"Sales tax on 250 = 18.75"`

## Calling a Method

You call a method by specifying a receiver, the name of the method, and optionally some parameters and an associated block.

    connection.downloadMP3("jitterbug") { |p| showProgress(p) }

In this example, the object `connection` is the receiver, `downloadMP3` is the name of the method, `"jitterbug"` is the parameter, and the stuff between the braces is the associated block.

For class and module methods, the receiver will be the class or module name.

    File.size("testfile")
    Math.sin(Math::PI/4)

If you omit the receiver, it defaults to `self`, the current object.

`self.id` | » | `537794160`
`id` | » | `537794160`
`self.type` | » | `Object`
`type` | » | `Object`

This defaulting mechanism is how Ruby implements private methods. Private methods may not be called with a receiver, so they must be methods available in the current object.

The optional parameters follow the method name. If there is no ambiguity you can omit the parentheses around the argument list when calling a method.[Other Ruby documentation sometimes calls these method calls without parentheses ``commands.''] However, except in the simplest cases we don't recommend this---there are some subtle problems that can trip you up.[In particular, you must use parentheses on a method call that is itself a parameter to another method call (unless it is the last parameter).] Our rule is simple: if there's any doubt, use parentheses.

    a = obj.hash    # Same as
    a = obj.hash()  # this.

    obj.someMethod "Arg1", arg2, arg3   # Same thing as
    obj.someMethod("Arg1", arg2, arg3)  # with parentheses.

### Expanding Arrays in Method Calls

Earlier we saw that if you put an asterisk in front of a formal parameter in a method definition, multiple arguments in the call to the method will be bundled up into an array. Well, the same thing works in reverse.

When you call a method, you can explode an array, so that each of its members is taken as a separate parameter. Do this by prefixing the array argument (which must follow all the regular arguments) with an asterisk.

`def five(a, b, c, d, e)`
`"I was passed #{a} #{b} #{c} #{d} #{e}"`
`end`
``
`five(1, 2, 3, 4, 5 )` | » | `"I was passed 1 2 3 4 5"`
`five(1, 2, 3, *['a', 'b'])` | » | `"I was passed 1 2 3 a b"`
`five(*(10..14).to_a)` | » | `"I was passed 10 11 12 13 14"`

### Making Blocks More Dynamic

We've already seen how you can associate a block with a method call.

    listBones("aardvark") do |aBone|
      # ...
    end

Normally, this is perfectly good enough---you associate a fixed block of code with a method, in the same way you'd have a chunk of code after an `if` or `while` statement.

Sometimes, however, you'd like to be more flexible. For example, we may be teaching math skills.[Of course, Andy and Dave would have to learn math skills first. Conrad Schneiker reminded us that there are three kinds of people: those who can count and those who can't.] The student could ask for an n-plus table or an n-times table. If the student asked for a 2-times table, we'd output 2, 4, 6, 8, and so on. (This code does not check its inputs for errors.)

    print "(t)imes or (p)lus: "
    times = gets
    print "number: "
    number = gets.to_i

    if times =~ /^t/
      puts((1..10).collect { |n| n*number }.join(", "))
    else
      puts((1..10).collect { |n| n+number }.join(", "))
    end

produces:

    (t)imes or (p)lus: t
    number: 2
    2, 4, 6, 8, 10, 12, 14, 16, 18, 20

This works, but it's ugly, with virtually identical code on each branch of the `if` statement. If would be nice if we could factor out the block that does the calculation.

    print "(t)imes or (p)lus: "
    times = gets
    print "number: "
    number = gets.to_i

    if times =~ /^t/
      calc = proc { |n| n*number }
    else
      calc = proc { |n| n+number }
    end
    puts((1..10).collect(&calc).join(", "))

produces:

    (t)imes or (p)lus: t
    number: 2
    2, 4, 6, 8, 10, 12, 14, 16, 18, 20

If the last argument to a method is preceded by an ampersand, Ruby assumes that it is a `Proc` object. It removes it from the parameter list, converts the `Proc` object into a block, and associates it with the method.

This technique can also be used to add some syntactic sugar to block usage. For example, you sometimes want to take an iterator and store each value it yields into an array. We'll reuse our Fibonacci number generator from page 40.

`a = []`
`fibUpTo(20) { |val| a << val }` | » | `nil`
`a.inspect` | » | `"[1, 1, 2, 3, 5, 8, 13]"`

This works, but our intention isn't quite as transparent as we may like. Instead, we'll define a method called `into`, which returns the block that fills the array. (Notice at the same time that the block returned really is a closure---it references the parameter anArray even after method `into` has returned.)

`def into(anArray)`
`return proc { |val| anArray << val }`
`end`
``
`fibUpTo 20, &into(a = [])`
`a.inspect` | » | `"[1, 1, 2, 3, 5, 8, 13]"`

### Collecting Hash Arguments

Some languages feature ``keyword arguments''---that is, instead of passing arguments in a given order and quantity, you pass the name of the argument with its value, in any order. Ruby 1.6 does not have keyword arguments (although they are scheduled to be implemented in Ruby 1.8).

In the meantime, people are using hashes as a way of achieving the same effect. For example, we might consider adding a more powerful named-search facility to our `SongList`.

    class SongList
      def createSearch(name, params)
        # ...
      end
    end
    aList.createSearch("short jazz songs", {
                       'genre'            => "jazz",
                       'durationLessThan' => 270
                       } )

The first parameter is the search name, and the second is a hash literal containing search parameters. The use of a hash means that we can simulate keywords: look for songs with a genre of ``jazz'' and a duration less than 4 1/2 minutes. However, this approach is slightly clunky, and that set of braces could easily be mistaken for a block associated with the method. So, Ruby has a short cut. You can place key `=>` value pairs in an argument list, as long as they follow any normal arguments and precede any array and block arguments. All these pairs will be collected into a single hash and passed as one argument to the method. No braces are needed.

    aList.createSearch("short jazz songs",
                       'genre'            => "jazz",
                       'durationLessThan' => 270
                       )

Previous < | Contents ^ | Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.