programming.nbk: Home | Index | Next Page: Ruby: Names | Previous Page: Ruby: load


 Ruby: Methods

Method definition:

    def method_name {(argument_list) }
        code
    end

Each object can only have one method with any given name. Because of this, method overloading cannot be performed in the same manner as C++ or Java. However, a method can test the number of arguments it recieved, and perform different actions based on the number:

    # The Rectangle constructor accepts arguments in either   
    # of the following forms:   
    #   Rectangle.new([x_top, y_left], length, width)   
    #   Rectangle.new([x_top, y_left], [x_bottom, y_right])   
    class Rectangle   
        def initialize(*args)   
            if args.size < 2  || args.size > 3   
                # modify this to raise exception, later   
                puts 'This method takes either 2 or 3 arguments'  
            else  
                if args.size == 2   
                    puts 'Two arguments'  
                else  
                    puts 'Three arguments'  
                end  
            end  
        end  
    end  
    Rectangle.new([10, 23], 4, 10)   
    Rectangle.new([10, 23], [14, 13])

programming.nbk: Home | Index | Next Page: Ruby: Names | Previous Page: Ruby: load


Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time