0

我有一个为子类化而构建的类。

class A
  def initialize(name)
  end

  def some
    # to define in subclass
  end
end

# usage
p A.new('foo').some
#=> nil

在我的用例中,我不想创建子类,因为我只需要一个实例。因此,我将更改initialize方法以支持以下用法。

p A.new('foo') { 'YEAH' }.some
#=> YEAH

我怎么能支持上面的用法?


顺便说一句:我为 Ruby 1.8.7 项目找到了以下解决方案,但它们对我来说看起来很尴尬。

class A
  def singleton_class
    class << self; self; end
  end

  def initialize(name, &block)
    @name = name
    self.singleton_class.send(:define_method, :some) { block.call } if block_given?
  end

  def some
    # to define in subclass
  end
end
4

1 回答 1

3

您可以将块参数存储在实例变量中,call然后再存储:

class A
  def initialize(name, &block)
    @name  = name
    @block = block
  end

  def some
    @block.call
  end
end

A.new('foo') { 'YEAH' }.some
#=> "YEAH"

您还可以将参数传递到块中:

class A
  # ...
  def some
    @block.call(@name)
  end
end

A.new('foo') { |s| s.upcase }.some
#=> "FOO"

或者instance_exec接收者上下文中的块:

class A
  # ...

  def some
    instance_exec(&@block)
  end
end

这允许您绕过封装:

A.new('foo') { @name.upcase }.some
#=> "FOO"
于 2017-09-26T09:58:25.877 回答