Methods
In other programming languages the term you might use for a Ruby method is function, procedure, or subroutine. In Ruby everything is a method — a named piece of code that does a job, optionally takes arguments, and optionally returns a value.
Method names are written in snake_case.
|
Ruby has two kinds of methods: class methods and instance methods. You will meet both in the Classes and Objects chapter. For now, treat every method as a standalone piece of code. |
Defining a Method
Suppose we repeat the same three lines of code in a program (for whatever reason):
puts 'Hello World!'
puts 'Hello World!'
puts 'Hello World!'
We can bundle these three lines into a method called three_times:
def three_times
puts 'Hello World!'
puts 'Hello World!'
puts 'Hello World!'
end
Let’s test this in irb with load './hello-worldx3b.rb', which
reads the file and makes its definitions available:
$ irb
>> load './hello-worldx3b.rb'
=> true
>> three_times
Hello World!
Hello World!
Hello World!
=> nil
>> exit
Parameters
Methods become much more useful when you can pass values into them. Parameters turn a fixed method into a flexible one:
def three_times(value)
puts value
puts value
puts value
end
$ irb
>> load './hello-worldx3c.rb'
=> true
>> three_times('Hello World!')
Hello World!
Hello World!
Hello World!
=> nil
The parentheses around the argument are optional:
>> three_times 'Hello World!'
Hello World!
Hello World!
Hello World!
=> nil
|
Ruby gurus will turn up their noses at "unnecessary" brackets in your programs and probably pepper you with comparisons to Java. There is one simple rule in the Ruby community: the fewer brackets, the cooler you are. ;-) You won’t get a medal for using fewer brackets, though. Decide for yourself what makes you happy. |
If you call a method without the required argument you get an
ArgumentError:
>> three_times
ArgumentError: wrong number of arguments (given 0, expected 1)
Default Values
You can give a parameter a default, which lets callers skip it:
def three_times(value = 'blue')
puts value
puts value
puts value
end
$ irb
>> load './hello-worldx3d.rb'
=> true
>> three_times('Example')
Example
Example
Example
=> nil
>> three_times
blue
blue
blue
=> nil
>> exit
return
puts is nice for printing but most methods exist to produce a
value. The return keyword ships a value back to the caller:
def area_of_a_circle(radius)
pi = 3.14
area = pi * radius * radius
return area
end
$ irb
>> load './circle-a.rb'
=> true
>> area_of_a_circle(10)
=> 314.0
>> exit
Ruby lets you skip return — a method automatically returns the
value of its last expression:
def area_of_a_circle(radius)
pi = 3.14
area = pi * radius * radius
area
end
You can go one step further and drop the temporary variable too:
def area_of_a_circle(radius)
pi = 3.14
pi * radius * radius
end
All three versions are equivalent. Use return when it makes a
method easier to read — for an early exit, say. Otherwise the
implicit-return form is more idiomatic.