0

我需要创建一个类来防止外部代码直接实例化它。所有实例都是通过调用几个类方法获得的,还有一些实例方法会生成新实例并返回它们。

class SomeClass
  class << self
    private :new, :allocate
  end

  def initialize(hash)
    @hash = hash
  end

  # A class method that returns a new instance
  def self.empty
    new({})   # works fine!
  end

  # Another class method that returns a new instance
  def self.double(a, b)
    new({a => b})   # works fine!
  end

  # An instance method that will generate new instances
  def combine_with(a, b)
    # Here's the problem!
    # Note: it doesn't work with self.class.new either
    SomeClass.new(@hash.merge({a => b}))
  end
end

所以我将new方法定义为私有的。这适用于类方法,在它们内部我仍然可以在内部调用 new。但我不能new从实例方法中调用。我尝试将其定义new为受保护,但这也无济于事。

4

1 回答 1

1

你试过用send吗?

SomeClass.send :new, @hash.merge({a => b})
于 2012-11-30T17:06:09.687 回答