ruby super keyword

后端 未结 6 1267
天命终不由人
天命终不由人 2020-12-12 20:45

From what I understand, super keyword invokes a method with the same name as the current method in the superclass of the current class. Below in the autol

6条回答
  •  孤城傲影
    2020-12-12 21:07

    The example provided in the Ruby Docs for the super keyword:

    module Vehicular
      def move_forward(n)
        @position += n
      end
    end
    
    class Vehicle
      include Vehicular  # Adds Vehicular to the lookup path
    end
    
    class Car < Vehicle
      def move_forward(n)
        puts "Vrooom!"
        super            # Calls Vehicular#move_forward
      end
    end
    

    Inspecting ancestors

    puts Car.ancestors.inspect
    
    # Output
    # [Car, Vehicle, Vehicular, Object, Kernel, BasicObject]
    

    Note the inclusion of the Vehicular Module object!

提交回复
热议问题