gpt4 book ai didi

ruby - 从另一个模块覆盖模块方法

转载 作者:数据小太阳 更新时间:2023-10-29 06:44:16 24 4
gpt4 key购买 nike

我想从另一个模块 B 覆盖模块 A 的方法,该方法将对 A 进行猴子补丁。
http://codepad.org/LPMCuszt

module A
def foo; puts 'A' end
end

module B
def foo; puts 'B'; super; end
end

A.module_eval { include B } # why no override ???

class C
include A
end

# must print 'A B', but only prints 'A' :(
C.new.foo

最佳答案

module A
def foo
puts 'A'
end
end

module B
def foo
puts 'B'
super
end
end

include A # you need to include module A before you can override method

A.module_eval { include B }

class C
include A
end

C.new.foo # => B A

关于ruby - 从另一个模块覆盖模块方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4900167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com