Ruby中的方法覆盖

时间:2011-10-19 22:49:05

标签: ruby methods overloading

我的代码如下:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end

我想在B类中编写一个看起来像这样的方法

class B
   def b(a)
      if a==2     # are you sure? same result as the old method
         3
      else
         A.b(a)
      end
   end
end

我如何在Ruby中执行此操作?

2 个答案:

答案 0 :(得分:7)

你想要super函数,它调用函数的'previous'定义:

module A
  def b(a)
    p 'A.b'
  end
end

class B
  include A

  def b(a)
    if a == 2
      p 'B.b'
    else
      super(a) # Or even just `super`
    end
  end
end

b = B.new
b.b(2) # "B.b"
b.b(5) # "A.b"

答案 1 :(得分:3)

class B
  alias old_b b  # one way to memorize the old method b , using super below is also possible

  def b(a)
    if a==2
        '3'     # returning a string here, so you can see that it works
    else
      old_b(a)   # or call super here
    end
  end
end



ruby-1.9.2-p0 >   x = B.new
 => #<B:0x00000001029c88> 
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 >   x.b(1) 
 => 2 
ruby-1.9.2-p0 > x.b(2)
 => "3"
ruby-1.9.2-p0 > x.b(3)
 => 4