簡體   English   中英

Ruby-如何為類方法模仿super?

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

為了(自動)教育目的,我正在嘗試模仿super行為以了解其工作原理。

我可以為實例方法模仿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)

有任何想法嗎?

好吧,問題可能出在您使用的Ruby版本。 我正在運行1.9.2,並且程序按預期運行。 我認為(從您代碼的注釋中)問題是您正在運行Ruby v1.8.7。 再次嘗試運行代碼也沒有什么壞處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM