面试题答案
一键面试在Ruby中,当一个类C
同时混入了模块A
和B
,且这两个模块都定义了同名方法method
,Ruby会按照混入模块的顺序来确定调用哪个模块的method
方法。先混入的模块中的方法会被优先调用。
例如,如果代码是这样:
module A
def method
puts "This is method from module A"
end
end
module B
def method
puts "This is method from module B"
end
end
class C
include A
include B
end
c = C.new
c.method
上述代码中,C
类先include
了A
模块,再include
了B
模块,那么调用c.method
会输出 "This is method from module A"。
如果要手动指定调用特定模块的method
方法,可以使用模块名作为前缀来调用。例如,要调用模块B
的method
方法,可以这样做:
c = C.new
B.method(c)
这里通过B.method(c)
的方式手动调用了模块B
的method
方法,并将c
作为接收者传递进去。这种方式通常用于需要明确调用特定模块中同名方法的场景。