Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有模块mixin的Ruby类_Ruby_Oop - Fatal编程技术网

带有模块mixin的Ruby类

带有模块mixin的Ruby类,ruby,oop,Ruby,Oop,我正在尝试为mixin扩展类中的模块方法 这是我的密码: module Mod_1 def bar puts "xxx" end end class Class_A include Mod_1 def bar super puts "yyy" end end test = Class_A.new test.bar 我能想到的最好的方法是: module Mod_1 def Mod_1.foo

我正在尝试为mixin扩展类中的模块方法

这是我的密码:

module Mod_1
    def bar
        puts "xxx"
    end
end

class Class_A
    include Mod_1
    def bar
        super
        puts "yyy"
     end
end

test = Class_A.new
test.bar
我能想到的最好的方法是:

module Mod_1
    def Mod_1.foo
        puts "aaa"
    end
end

class Class_A
    include Mod_1
    def foo
        Mod_1.foo
        puts "bbb"
     end
end

test = Class_A.new
test.foo
有更好的方法吗?

请参见以下内容:

module Bar
    def foo
        puts "first"
    end
end

class Class_A
    include Bar
    alias old_foo foo
    def foo
        old_foo
        puts "second"
    end
end

Class_A.new.bar
返回:

"first"
"second"
这使用了别名。我建议你专门为Ruby查找一些东西,比如你正在尝试做的事情

阅读:

您的代码有问题吗?如果是,是什么?如果没有,问题是什么?问题是我有没有更好的方法来做我想做的事。你到底想做什么?为什么这种方法对你来说不够好?你可以扩展一个模块,但不能扩展一个模块方法。他的第一个代码片段也是这样工作的(与
super
)。在1.9.3版上试用,验证代码是否有效。也将尝试使用“super”。仅当您需要将
Class_A.new.bar
更改为
Class_A.new.foo
使用
super
时,在使用别名/重命名方法之前,强烈建议您使用
super
,因为它遵循正确的继承链,不会绕过它。如果你对周围的事物进行别名,那么你将很难真正找到在出现问题时被调用的方法。我明白了,从现在起,你一定要记住这一点