4

使用している私のコードがありますSimpleDelegator

require 'delegate'

class Foo < SimpleDelegator
  def meth
    p 'new_meth'
  end
end

class Bar
  def meth
    p 'old_meth'
  end

  def bar_meth
    meth
  end
end

bar = Bar.new
foo = Foo.new(bar)
foo.meth      #=> "new_meth"
foo.bar_meth  #=> "old_meth"

なぜ最後の行が与えるの"old_meth"ですか???!!! ありがとう!

4

1 に答える 1

4

Delegator言って:

このライブラリは、メソッド呼び出しをオブジェクトに委譲する 3 つの異なる方法を提供します。最も使いやすいのはSimpleDelegatorです。オブジェクトをコンストラクターに渡すと、オブジェクトがサポートするすべてのメソッドが委任されます。このオブジェクトは後で変更できます。

さて、シンボルの右側にある出力を見てください# =>

require 'delegate'

class Foo < SimpleDelegator
  def meth
    p 'new_meth'
  end
end

class Bar
  def meth
    p 'old_meth'
  end

  def bar_meth
    self.method(:meth)
  end
end

bar = Bar.new # => #<Bar:0x8b31728>
foo = Foo.new(bar)
foo.__getobj__ # => #<Bar:0x8b31728>
foo.bar_meth # => #<Method: Bar#meth>
foo.method(:meth) # => #<Method: Foo#meth>

したがって、行を使用するfoo.method(:meth)と、output( )は、#<Method: Foo#meth>呼び出すたびに、クラスのメソッドが呼び出されることを確認します。foo.methmethFoofoo.bar_meth#<Method: Bar#meth>bar_methmethBar#meth

SimpleDelegatorそれを言って:

Delegator の具体的な実装であるこのクラスは、サポートされているすべてのメソッド呼び出しをコンストラクターに渡されたオブジェクトに委譲する手段を提供し、委譲先のオブジェクトを後で # setobjで変更することさえできます。

はい、あなたの場合、を使用してオブジェクトがオブジェクトfooに設定されています。行の出力はそれを示しています。bar#__setobj__foo.__getobj__

于 2013-08-10T16:49:57.670 に答える