Ruby Programming/Writing methods

From Wikibooks, open books for an open world
Jump to: navigation, search

← Data types | Classes and objects →


Defining Methods[edit]

Methods are defined using the def keyword and ended with the end keyword. Some programmers find the Methods defined in Ruby very similar to those in Python.

    def myMethod
    end

To define a method that takes in a value, you can put the local variable name in parentheses after the method definition. The variable used can only be accessed from inside the method scope.

    def myMethod(msg)
        puts msg
    end

If multiple variables need to be used in the method, they can be separated with a comma.

    def myMethod(msg, person)
        puts "Hi, my name is " + person + ". Some information about myself: " + msg
    end

Any object can be passed through using methods.

    def myMethod(myObject)
        if(myObject.is_a?(Integer))
              puts "Your Object is an Integer"
        end
        #Check to see if it defined as an Object that we created
        #You will learn how to define Objects in a later section
        if(myObject.is_a?(MyObject))
              puts "Your Object is a MyObject"
        end
    end

The return keyword can be used to specify that you will be returning a value from the method defined.

    def myMethod
        return "Hello"
    end

It is also worth noting that ruby will return the last expression evaluated, so this is functionally equivalent to the previous method.

    def myMethod
        "Hello"
    end

Some of the Basic Operators can be overridden using the def keyword and the operator that you wish to override.

    def ==(oVal)
        if oVal.is_a?(Integer)
            #@value is  a variable defined in the class where this method is defined
            #This will be covered in a later section when dealing with Classes
            if(oVal == @value)
                return true
            else
                return false
            end
        end
    end