Optinmonster Test

Head First Ruby Notes

Chapter 2 – Getting Organized

Defining Methods

Method definitions look like this in Ruby:

def print_sum(arg1, arg2)
    print arg1 + arg2
end

If you want calls to your method to include arguments, you’ll need to add parameters to the method definition. Parameters appear after the method name, within parenthesis. Each argument on the method call gets stored in one of the parameters within the method.

The method body consists of one or more Ruby statements that are executed when the method is called.

Calling Methods You’ve Defined

You can call methods you’ve defined just like any other. For example:

def accelerate
    puts "Stepping on the gas"
    puts "Speeding up"
end

def sound_horn
    puts "Pressing the horn button"
    puts "Beep beep!"
end

def use_headlights(brightness)
    puts "Turning on #{brightness} headlights"
    puts "Watch out for deer!"
end

sound_horn
accelerate
use_headlights("hi-beam")

When we run the source file from the command line, we’ll see the result of our method calls!

ruby vehicle_methods.rb
Pressing the horn button
Beep beep!
Stepping on the gas
Speeding up
Turning on hi-beam headlights
Watch out for deer!

Method Names

The method name can be one or more lower-case words, separated by underscores. Numbers are legal, but rarely used.

It’s also legal for a method name to end in a question mark (?) or exclamation point (!). These endings have no special meaning to Ruby, but there are certain conventions around their use.

Lastly, it’s legal for a method name to end in an equal sign (=). Methods ending in this character are used as attribute writers. Ruby does treat this ending specially, so don’t use it for a regular method.

Parameters

If you need to pass data into your method, you can include one or more parameters after the method name, separated by commas. In your method body, parameters can be accessed just like any other variable.

def print_area(length, width)
    puts length * width
end

Optional Parameters

Sometimes, you do not need the parameters. In this case, you can make the parameters optional. You can provide a default value in the method declaration, for example:

def order_soda(flavor, size = "medium", quantity = 1)
    if quantity == 1
        plural = "soda"
    else
        plural = "sodas"
    end
    puts "#{quantity} #{size} #{flavor} #{plural}, coming right up!"
end

Now, if you want to override the default, just provide an argument with the value you want. And if you’re happy with the default, you can skip the argument altogether. For example:

order_soda("orange")
order_soda("lemon-lime", "small", 2)
order_soda("grape", "large")

will print

1 medium orange soda, coming right up!
2 small lemon-lime sodas, coming right up!
1 large grape soda, coming right up!

Optional parameters need to appear after any other parameters you intend to use. If you make a required parameter following an optional parameter, you won’t be able to leave the optional parameter off.

Administrative: Loading Ruby file into irb

Type irb -I ., then require [filename]. For example:

irb -I .
require "vehicle_methods"

Return Value

Like most languages, Ruby methods have a return value, a value that they can send back to the code that called them. A Ruby method can return a value to its caller using the return keyword.

For example:

def mileage(miles_driven, gas_used)
    return miles_driven / gas_used
end

Then you can use the same method to calculate both types of mileage.

trip_mileage = mileage(400, 12)
puts "You got #{trip_mileage}" MPG on this trip."

Implicit Return Values

You don’t actually need a return keyword in the above method. The value of the last expression evaluated within a method automatically becomes the method’s return value. For example:

def mileage(miles_driven, gas_used)
    miles_driven / gas_used
end

Returning from a method early

The return keyword causes the method to exit, without running the lines of code that follow it. This is useful in situations where running that code would be pointless, or even harmful.

For example

def mileage(miles_driven, gas_used)
    if gas_used == 0
        return 0.0
    end
    miles_driven / gas_used
end

The above code will test whether gas_used is zero. If it is zero, return 0.0 instead.