使用 Ruby 中的参数调用 super, super class 方法
Calling super, super class method with parameters in Ruby
我找到了以下有效的解决方案 (link 1, link 2),它们调用祖父母方法但没有任何参数。有谁知道如何调用带参数的祖父母方法?
class GrandParent
def fun(word)
puts word
end
end
class Parent < GrandParent
def fun(word)
puts word + 'end'
end
end
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call
end
end
可以直接传参这样调用:
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call(param1, param2)
end
end
call
接受参数
GrandParent.instance_method(:fun).bind(self).call word
我不知道你的用例,但这是一个 Really Bad Idea™。它直接在 Child
和 GrandParent
之间创建了不必要的依赖关系,这样各种通常合理的重构都会导致崩溃,例如将 fun
移动到仅在 Parent
中实现,更改 Parent
以子类化不同但相似的父类,等等
我找到了以下有效的解决方案 (link 1, link 2),它们调用祖父母方法但没有任何参数。有谁知道如何调用带参数的祖父母方法?
class GrandParent
def fun(word)
puts word
end
end
class Parent < GrandParent
def fun(word)
puts word + 'end'
end
end
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call
end
end
可以直接传参这样调用:
class Child < Parent
def fun(word)
GrandParent.instance_method(:fun).bind(self).call(param1, param2)
end
end
call
接受参数
GrandParent.instance_method(:fun).bind(self).call word
我不知道你的用例,但这是一个 Really Bad Idea™。它直接在 Child
和 GrandParent
之间创建了不必要的依赖关系,这样各种通常合理的重构都会导致崩溃,例如将 fun
移动到仅在 Parent
中实现,更改 Parent
以子类化不同但相似的父类,等等