开发者

Calling Super Methods in Ruby

I am trying to define some classes in Ruby that have an inheritance hierarchy, but I want to use one of the methods in the base class in the derived class. The twist is that I don't want to call the exact method I'm in, I want to call a different one. The following doesn't work, but it's what I want to do (basically).

class A
    def foo
        puts 'A::foo'
 开发者_C百科   end
end

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


Probably, this is what you want?

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


A more general solution.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜