假设我有两个这样的类:
class Parent
def say
"I am a parent"
end
end
class Child < Parent
def say
"I am a child"
end
def super_say
#I want to call Parent.new#say method here
end
end要做到这一点,有哪些选择?我想到的是:
def super_say
self.superclass.new.say #obviously the most straight forward way, but inefficient
end
def super_say
m = self.superclass.instance_method(:say)
m = m.bind(self)
m.call
#this works, but it's quite verbose, is it even idiomatic?
end我正在寻找一种方法,它不涉及将Parent.new#say别名为其他东西,这将使它在方法查找链中是唯一的(或者这实际上是首选的方法吗?)。有什么建议吗?
发布于 2010-10-21 03:09:44
我倾向于使用别名。(我不太确定我是否理解您的反对意见。)
示例:
class Child < Parent
alias :super_say :say
def say
"I am a child"
end
end提供:
irb(main):020:0> c = Child.new
=> #<Child:0x45be40c>
irb(main):021:0> c.super_say
=> "I am a parent"发布于 2010-10-20 23:45:51
你的第二个解决方案( bind())就是我想要的。它是冗长的,因为您所做的非常不寻常,但如果您确实需要这样做--这个解决方案对我来说似乎很好。
https://stackoverflow.com/questions/3979263
复制相似问题