鑑於以下類Ruby Metaprogramming:檢查是否由父類調用?
class Parent
def hello
puts "I am the parent class"
end
def call_parent_hello
hello
end
end
class Child < Parent
def hello
puts "I am the child class"
end
end
當我執行以下操作:
c = Child.new
c.hello # => Outputs: "I am the child class"
c.call_parent_hello # => Outputs: "I am the child class"
是否有可能使Child#call_parent_hello
訪問Parent#hello
,但不改變Parent
類?
我要尋找某種called_by_parent_class?
實現這樣的:
def hello
if called_by_parent_class?
super
else
puts "I am the child class"
end
end
這將輸出'「我是父類」'2倍。我希望第一次調用輸出'「我是孩子班級」',第二次打印'「我是父母班級」'。 – iblue 2012-07-07 17:28:16
伊斯蘭會議組織。那麼,我只是錯誤的方法,那麼你需要重寫'call_parent_hello'。關鍵是你的問題的答案是「使用'super'關鍵字!」你可能喜歡閱讀這篇關於Ruby的方法查找過程的文章http://blog.rubybestpractices.com/posts/gregory/030-issue-1-method-lookup.html – 2012-07-07 17:44:13
(看着你更新的「我在找什麼.. 。「問題) - 你可以使用'Kernel.caller'(但在幾乎所有情況下,這是一個設計錯誤) – 2012-07-07 17:50:07