使用块初始化对象

时间:2022-06-29 21:28:32

Is it possible to initialize an object with a block as follows?

是否可以使用块初始化对象,如下所示?

class Foo
  attr_reader :bar,:baz
  def initialize(bar,baz)
    @bar, @baz = bar, baz
  end
end

Foo.new do |bar, baz|
  # some logic to be implemented
  # @bar, @baz to be assigned
end

1 个解决方案

#1


15  

Of course, you can yield from within initialize, there's nothing special about it:

当然,你可以从初始化中得出,没有什么特别之处:

class Foo
  attr_accessor :bar, :baz
  def initialize
    yield self
  end
end

Foo.new do |f|
  f.bar = 123
  f.baz = 456
end
#=> <Foo:0x007fed8287b3c0 @bar=123, @baz=456>

You could also evaluate the block in the context of the receiver using instance_eval:

您还可以使用instance_eval在接收器的上下文中评估块:

class Foo
  attr_accessor :bar, :baz
  def initialize(&block)
    instance_eval(&block)
  end
end

Foo.new do
  @bar = 123
  @baz = 456
end
#=> #<Foo:0x007fdd0b1ef4c0 @bar=123, @baz=456>

#1


15  

Of course, you can yield from within initialize, there's nothing special about it:

当然,你可以从初始化中得出,没有什么特别之处:

class Foo
  attr_accessor :bar, :baz
  def initialize
    yield self
  end
end

Foo.new do |f|
  f.bar = 123
  f.baz = 456
end
#=> <Foo:0x007fed8287b3c0 @bar=123, @baz=456>

You could also evaluate the block in the context of the receiver using instance_eval:

您还可以使用instance_eval在接收器的上下文中评估块:

class Foo
  attr_accessor :bar, :baz
  def initialize(&block)
    instance_eval(&block)
  end
end

Foo.new do
  @bar = 123
  @baz = 456
end
#=> #<Foo:0x007fdd0b1ef4c0 @bar=123, @baz=456>