2011-04-25 20 views
0

對於(自動)教育目的,我試圖模仿super行爲來了解它的工作原理。Ruby - 如何模仿超類方法?

我可以模仿super作爲實例方法,但我無法爲類方法做到這一點。

這裏是我的代碼:

class A 
    def aa 
    @msg ||= 'Original...: ' 
    puts "#{@msg}#{self}.aa: #{self.class} < #{self.class.superclass}" 
    end 
    def self.ab 
    @msg ||= 'Original...: ' 
    puts "#{@msg}#{self}.ab: #{self} < #{self.superclass}" 
    end 
end 

class B < A 
    def aa 
    @msg = "Real super.: " 
    super 
    end 
    def self.ab 
    @msg = "Real super.: " 
    super 
    end 
    def mimic_aa 
    @msg = "Mimic super: " 
    self.class.superclass.instance_method(:aa).bind(self).call 
    end 
    def self.mimic_ab 
    @msg = "Mimic super: " 
    #superclass.method(:ab).unbind.bind(self).call 
     #=> Error: singleton method only works in original object 

    #superclass.ab 
     #=> self is A; I want self to be B 

    proc = superclass.method(:ab).to_proc 

    #self.instance_eval(&proc) 
     #=> ArgumentError: instance_eval seems to call aa(some_unwanted_param) 
     # Note: Ruby 1.8.7 

    #eval('proc.call', binding) 
     #=> self is A; I want self to be B 

    end 
end 

a = A.new 
b = B.new 

a.aa   #=> Original...: #<A:0xb77c66ec>.aa: A < Object 
b.aa   #=> Real super.: #<B:0xb77c6624>.aa: B < A 
b.mimic_aa #=> Mimic super: #<B:0xb77c6624>.aa: B < A 

puts '' 

A.ab   #=> Original...: A.ab: A < Object 
B.ab   #=> Real super.: B.ab: B < A 
B.mimic_ab #=> (expected the same as above) 

任何想法?

+0

你的問題太複雜了,不清楚。我想這就是爲什麼你的問題到目前爲止還沒有得到解答。你想用'B#mimic_aa'和'B.mimic_ab'做什麼?爲什麼'B#aa'和'B.ab'不夠?另外,方法名稱很混亂。你可能想改善這個問題。 – sawa 2011-04-25 01:36:13

+0

@sawa,我想了解如何在B作爲'self'的上下文中執行A中的類方法。當A和B中的方法名稱不同時,它會很有用,所以我不能使用'super'。無論如何,謝謝你,我會考慮改進這個問題。 :) – 2011-04-25 01:59:26

回答

1

那麼,問題可能是你使用的Ruby版本。我正在運行1.9.2,程序按預期運行。我認爲(從您的代碼中的評論),問題是您正在運行Ruby v1.8.7。再次嘗試運行你的代碼也不會有什麼壞處。

+0

酷!你使用'self.instance_eval(&proc)'? – 2011-12-14 12:07:06

+0

這是工作的定義:'def self.mimic_ab; @msg =「模仿超級:」; superclass.method(:AB).unbind.bind(個體).CALL;結束' – Tom 2012-01-13 05:51:52

+0

我使用1.9.2進行了測試,並且按照您的說法工作!謝謝! :) – 2012-01-17 17:39:38