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
    • 229
    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:

     

    class Object
      def initialize (name)
        @name=name
      end
      def display
        puts @name
       end
    end
    obj = Object.new("Rahul")   #creating the object of the class
    obj.display
    
    

     

    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:

     

    class Apple 
      def self.fruit #self is a class method
        puts "An Apple is an healthy fruit" 
      end 
    end 
    
    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 :

     

    class Apple
    
      class << self         #Another way of writing the class method
        def fruit
          puts "An Apple is an healthy fruit"
        end
      end
    end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: