Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Class Methods And Object Methods

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 245
    Comment on it

    Object Methods:

     

    • Object Methods are thode methods which we have to explicitly define in the class.
    • First we have to create an object of the class and then we call the object methods.

    Example:

     

    1. class Object
    2. def initialize (name)
    3. @name=name
    4. end
    5. def display
    6. puts @name
    7. end
    8. end
    9. obj = Object.new("Rahul") #creating the object of the class
    10. obj.display
    11.  
    12.  

     

    Output:   Rahul

     


    Class Methods:

     

    • Class Methods are those methods which are implicitly defined in the class itself.
    • We do not have to define the class methods on our own.
    • For class methods we do not have to create objects for them.
    • They are called directly by using the name of the class.

     

    Example:

     

    1. class Apple
    2. def self.fruit #self is a class method
    3. puts "An Apple is an healthy fruit"
    4. end
    5. end
    6.  
    7. Apple.fruit #Invoking the fruit method by using the name of the class Apple

     

    Output: An Apple is an healthy fruit

     

    • As we can see in that fruit is a method of the Apple class.
    • Self is a class method which is defined on the fruit method definition.
    • Another way of writing the class method is :

     

    1. class Apple
    2.  
    3. class << self #Another way of writing the class method
    4. def fruit
    5. puts "An Apple is an healthy fruit"
    6. end
    7. end
    8. end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: