dav*_*orb 3 ruby methods overloading
我的代码看起来像这样:
module A
def b(a)
a+1
end
end
class B
include A
end
Run Code Online (Sandbox Code Playgroud)
我想在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
Run Code Online (Sandbox Code Playgroud)
我如何在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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6803 次 |
| 最近记录: |