2011-04-25 43 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