ruby - 奇怪的 SimpleDelegator 行为

标签 ruby delegation

我的代码使用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"???!!!谢谢!

最佳答案

Delegator 说:

This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.

好的,现在看一下输出,它位于符号# => 的右边。 .

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) 行时,然后输出( #<Method: Foo#meth> )确认无论何时您将调用 foo.meth , 然后 meth Foo 的方法类将被调用。但是行 foo.bar_meth outputs( #<Method: Bar#meth> ) 只是说在方法内部 bar_meth , 如果你打电话 meth然后方法,Bar#meth将被调用。

SimpleDelegator 说:

A concrete implementation of Delegator, this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with #setobj.

是的,在你的情况下foo对象已设置为 bar对象,通过使用 #__setobj__ . foo.__getobj__ 行的输出正在表明这一点。

关于ruby - 奇怪的 SimpleDelegator 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163877/

相关文章:

ruby - ruby 方法定义中关键字参数的哈希上的 splat 运算符

mysql - 计算 Rails 中的日期列

ruby - Ruby 中 x.inspect 和 x.to_s 的区别?

iphone - 为异步 NSURLConnection 重构我的代码

design-patterns - 策略模式和委托(delegate)模式的区别

ruby-on-rails - 删除由匹配双括号分隔的子字符串的正则表达式

python - Ruby on Rails 与 Python

python - 在 Python 中自定义不可变类型

ruby - Ruby 中的委托(delegate)是什么?

javascript - 什么时候不应该使用事件委托(delegate)?