Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using super in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 238
    Comment on it

    With inheritance in ruby we can share parent class behavior to child classes. We can also override these methods in child classes.

      A built-in function called super is provided by Ruby. This method allows us to call methods up the inheritance hierarchy. When super is called from within a method, it will search the inheritance hierarchy for a method by the same name and then invoke it.

     

    class Vehicle
      attr_accessor :model, :company
    
      def initialize(model , company)
        @model = model
        @company = company
      end
    
      def top_speed
        100
      end
    end
    
    
    class Car < Vehicle
    
      def top_speed
        150
      end
    end
    
    
    class Bike < Vehicle
    
      def top_speed
        # passes execution to super class method
        super
      end
    end
    
    
    car = Car.new("Civic", "Honda")
    car.top_speed # => 150
    
    
    bike = Bike.new("Pulsar", "Bajaj")
    bike.top_speed # => 100    


    In have classes we have Vehicle super class. Car and Bike classes are inheriting from Vehicle. In child classes we have overridden "top_speed" methods. If you noticed in Bike class we have used super in method "top_speed", it class super class method and returns value 100.


    Lets pass parameter using super:

    class Vehicle
      attr_accessor :model, :company
    
      def initialize(model , company)
        @model = model
        @company = company
      end
    
      def top_speed
        100
      end
    end
    
    
    class Car < Vehicle
      attr_reader :color, :engine
      def initialize( engine, color , model , company)
        @engine = engine
        @color = color
        super(model, company)
      end
    
      def top_speed
        150
      end
    end


    Here in our Car class we have added two more properties engine and color. We will pass model and company parameters in super.

    car = Car.new("petrol", "red", "civic", "honda")
    car.color # => "red"
    car.company # => "honda"

     

 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: