Chapter 8. Passing Arguments and Returning Values

image with no caption

In this chapter, you’ll be looking at many of the effects (and side effects) of passing arguments and returning values to and from methods. First, though, I’ll take a moment to summarize the types of methods you’ve used up to now.

Summarizing Instance, Class, and Singleton Methods

An instance method is declared inside a class definition and is intended for use by a specific object or “instance” of the class, like this:

methods.rb

class MyClass
    # declare instance method
    def instanceMethod
        puts( "This is an instance method" )
    end
end

    # create object
ob = MyClass.new
    # use instance method
ob.instanceMethod

A class method may be declared inside a class definition, in which case the method name may be preceded by the class name, or a class << self block may contain a “normal” method definition. Either way, a class method is intended for use by the class itself, not by a specific object, like this:

class MyClass
    # a class method
    def MyClass.classmethod1
        puts( "This is a class method" )
    end

    # another class method
    class << self
        def classmethod2
             puts( "This is another class method" )
        end
    end
end

    # call class methods from the class itself
MyClass.classmethod1
MyClass.classmethod2

Singleton methods are methods that are added to a single object and cannot be used by other objects. A singleton method may be defined by appending the method name to the object name followed by a dot or by placing a “normal” method definition inside an ObjectName << self block like this:

# create object
ob = MyClass.new

    # define a singleton method
def ob.singleton_method1
    puts( "This is a singleton method" )
end

    # define another singleton method
class << ob
    def singleton_method2
        puts( "This is another singleton method" )
    end
end

    # use the singleton methods
ob.singleton_method1
ob.singleton_method2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.232.189