Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of Super Keyword and Mixins In Ruby

    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 0
    • 0
    • 1.96k
    Comment on it

    Use of Super Keyword and Mixins In Ruby

    Super Keyword

    Ruby gives us with a built-in function called super that allows us to call methods which are present in its super class. 

    The use of inheritance is to make the overridden methods in a subclass do something additional  to what the method in the super class did. This allows us to modify the needs of the subclass.

    class Animal
      def speak
        "Hello!"
      end
    end
    
    class GoodDog < Animal
      def speak
        super + " from GoodDog class"
      end
    end
    
    sparky = GoodDog.new
    sparky.speak       
    
    
    #Output => "Hello! from GoodDog class"

     

    Mixins

    In object-oriented programming languages, when a class can inherit all the functions and features of more than one parent class or we can say that if a child class has more than one parent class then this feature is called multiple inheritance, but ruby doesn't support multiple inheritance but mixins eliminate the need of having multiple inheritance. So basically mixin is a class that contains methods which can be used by other classes without having to be the parent class of those other classes.

     module Walkable
        def walk
          "I'm walking!"
        end
      end
    
      class Animal; end
    
      class Fish < Animal
      end
    
      class Mammal < Animal
      end
    
      class Cat < Mammal
        include Walkable         # mixing in Walkable module
      end
    
      class Dog < Mammal
        include Walkable         # mixing in Walkable module
      end

    And now Cat and Dog objects can walk, but objects of other classes won't be able to:

    tommy = Dog.new

    tuna = Fish.new

    tiny = Cat.new

    tommy.walk  # => I'm walking! 
    tiny.walk   # => I'm walking! 
    tuna.walk    # => NoMethodError: undefined method `walk' for #<Cat:0x007fc453152308>

    In this example, we have created a anAnimal class with a instance method named walk. After that we have created dog and cat methods which are inheriting the Animal class also with a walk instance method to override the inherited method. 

    However, in the subclass' walk method we use super to invoke the walk method from the superclass, Animal, and then we increase the functionality by adding some more text data to it.

     

 2 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: