我有这样的代码:
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 中执行此操作?
最佳答案
您需要 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"
关于ruby - Ruby 中的方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829157/