【问题标题】:Calling Super Methods in Ruby在 Ruby 中调用超级方法
【发布时间】:2011-08-11 09:07:33
【问题描述】:

我试图在 Ruby 中定义一些具有继承层次结构的类,但我想在派生类中使用基类中的方法之一。扭曲是我不想调用我所在的确切方法,我想调用不同的方法。以下不起作用,但这是我想做的(基本上)。

class A
    def foo
        puts 'A::foo'
    end
end

class B < A
    def foo
        puts 'B::foo'
    end
    def bar
        super.foo
    end
end

【问题讨论】:

    标签: ruby inheritance methods super derived


    【解决方案1】:

    更通用的解决方案。

    class A
      def foo
        puts "A::foo"
      end
    end
    
    class B < A
      def foo
        puts "B::foo"
      end
      def bar
        # slightly oddly ancestors includes the class itself
        puts self.class.ancestors[1].instance_method(:foo).bind(self).call
      end
    end
    
    B.new.foo # => B::foo
    B.new.bar # => A::foo
    

    【讨论】:

      【解决方案2】:

      大概,这就是你想要的?

      class A
        def foo
          puts 'A::foo'
        end
      end
      
      class B < A
        alias bar :foo
        def foo
          puts 'B::foo'
        end
      end
      
      B.new.foo # => B::foo
      B.new.bar # => A::foo
      

      【讨论】:

      • 哦,嘿。这真的很方便。所以是alias #{new} :#{old}?
      • 对。关键是,alias 是即时评估的。所以如果你把alias放在B#foo的定义之后,就不行了。它将变为B#foo
      猜你喜欢
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2017-08-25
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      相关资源
      最近更新 更多