Переопределение метода в Ruby - PullRequest
3 голосов
/ 20 октября 2011

У меня есть код, который выглядит так:

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 ]

7 голосов
/ 20 октября 2011

Требуется функция super, которая вызывает «предыдущее» определение функции:

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"
3 голосов
/ 20 октября 2011
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 
...