2

(编辑以使问题更具体)

我想知道是否可以在另一个对象的上下文中执行单例方法,如下例所示:

class A
  def initialize
    @foo = 'foo'
  end
end

def A.singleton(*args)
  puts 'in singleton'
  puts @foo
end

A.new.instance_eval &A.method(:singleton)

# output is:
# - in singleton

# desired output:
# - in singleton
# - foo
4

2 回答 2

0

这是不可能的。事实上,当您尝试这样做时,Ruby 有一个特定的错误:

module Foo
  def self.bar
  end
end

class Baz
end

Foo.method(:bar).unbind.bind(Baz.new)
# TypeError: singleton method called for a different object

这确实是一个人为的限制,因为UnboundMethod#bind可以很容易地跳过类型检查并让你去做。但是,如果您可以使用不同的接收器调用单例方法,那将是一个根本的矛盾:单例方法是为单个实例定义的。这是有道理的,这是不允许的。

于 2015-02-19T20:32:27.377 回答
0

我不认为这是可能的。A::Singletons具有讽刺意味的是,它本身就是一个单例(在单例模式的意义上),因此,由于A::Singletons系统中只有一个单例,但A可能存在include于许多不同的模块中,因此无法知道在哪个模块中添加方法。

于 2015-02-18T15:53:30.607 回答