简体   繁体   English

Ruby-如何为类方法模仿super?

[英]Ruby - How to mimic super for class method?

For (auto-)educational purposes, I'm trying to mimic the super behavior to learn how it works. 为了(自动)教育目的,我正在尝试模仿super行为以了解其工作原理。

I could mimic super for instance methods, but I couldn't do it for class methods. 我可以为实例方法模仿super方法,但对于类方法却无法做到。

Here is my code: 这是我的代码:

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)

Any ideas? 有任何想法吗?

Well, the problem is probably the version of Ruby that you are using. 好吧,问题可能出在您使用的Ruby版本。 I'm running 1.9.2, and the program runs as expected. 我正在运行1.9.2,并且程序按预期运行。 I think (from the comment in your code) that the problem is that you are running Ruby v1.8.7. 我认为(从您代码的注释中)问题是您正在运行Ruby v1.8.7。 It also wouldn't hurt to try running your code again. 再次尝试运行代码也没有什么坏处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM