Chapter 4 Methods

A method refers to a task which an object is asked to perform. Ruby allows you to invoke a method of an object with a dot.

Methods remove redundancy. You can call methods whenever you need it. Define a method by entering def followed by the method name and parameters.

Example 1:

def method(name)
    puts + name +  ", this is a method." 
end
method('ruby')
--> ruby, this is a method.

Example 2:

ruby> "xyz'.length
      3

Example 2 invokes the length method of the object “xyz.”

It is necessary to know what methods are acceptable to an object.

Surround the arguments with parentheses when you give them to a method.

object.method(arg1, arg2)

Ruby offers a special variable self which refers to whatever object calls a method. You may, however, omit ”.self” from method calls from an object to itself:

self.method_name(args...)
is equal to
method_name(args...)
.
  • Currently 2.96/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 1 comments