Methods
From RubySpec
Contents |
Overview
Given that pretty well everything in Ruby is an object, there are no functions, only methods. They are defined with def...end and they may have rescue and ensure sections like begin...end.
def boing puts "Boing!" end
They may return values (except constructors -- initialize().) By default, they return the value of the last expression evaluated within the block.
Definition
Methods may be defined with the def keyword or via define_method().
Methods defined outside of a class belong to the class Object.
In recent versions of Ruby it has become possible to define methods with def inside methods. This was not the case earlier. (When did it change?)
Method Names
Method names are not limited to simple alphanumerics. Method names can also be operators, such as '+' or '<<'. There are some Ruby conventions regarding method name suffixes:
- The '!' suffix indicates a method that modifies its receiver, when a non-modifying method also exists.
- The '?' suffix indicates a method that tests some condition and returns the boolean result of the test.
When an '=' is appended to a method name, the method can be called with white space in between the method name and the equals sign:
class M
def foo=(x)
...
end
end
m = M.new
m.foo = 5 # calls the method, passes in 5 as x
Methods that end with '=' can also be used for multiple assignment:
n,m = M.new, M.new
N.foo, M.foo = 'bar', 'baz'
# same as N.foo=('bar'); M.foo=('baz')
And as arguments for blocks:
[1,2].each {|m.foo|} #calls m.foo=(1); m.foo=(2)
Operator methods
Binary operators simply have the same name as the operator, in this case the dot can be ommitted. Unary operators have the operator plus an at-sign as name:
class M
def +(o)
puts "M+#{o.inspect} called"
end
def -@
puts "M negative"
end
end
m+3 #same as m.+(3)
-m #same as m.-@()
Arguments
Default arguments
Methods may have default arguments.
def boings(n=5)
n.times do
puts "Boing!"
end
end
boings # => 5
# >> Boing!
# >> Boing!
# >> Boing!
# >> Boing!
# >> Boing!
boings(2) # => 2
# >> Boing!
# >> Boing!
Variable arguments
An argument may be preceded by * (asterisk, commonly refered to as a splat) to indicate a variable-length array of arguments. An * (asterisk) argument indicates that any remaining arguments to the call will be bundled into a single array object. This argument must be the last argument in the parameter list, or next to last if a block (&) argument is specified.
def print_them_args(*args)
args.each {|a| puts a}
end
print_them_args 5, 'hello' # ->
# >> 5
# >> hello
print_them_args 5, 'hello', 'goodbye' # ->
# >> 5
# >> hello
# >> goodbye
Block arguments
The last argument may be preceded & (ampersand) to indicate a block argument. When the method is passed a Block, a Proc (equivalent to one created with Proc.new) is assigned to the block argument. If no block is specified, nil is assigned to the block argument.
Method Invocation
Every method invocation has a receiver. If no receiver is specified, the value of 'self' is the receiver. Classes are also objects, so 'class methods' are normal methods with the class object as receiver.
Code inside a class declaration is executed in the order it is encoutered. In the context of a class, the value of self is the Class object, which is subclass of Module. A number of methods are available in Module that are intended to be used inside a class declaration, e.g:
class SuperFish
# add instance methods 'fins' and 'scales'
attr_reader :fins, :scales # Module#attr_reader
# add methods age and age=
attr_accessor :age
def to_s
"This superfish has #@fins fins, #@scales scales and is #@age years old."
end
end
fish=SuperFish.new
fish.age=3

