Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an object with a block

Tags:

ruby

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
like image 769
DreamWalker Avatar asked Dec 03 '15 12:12

DreamWalker


People also ask

What is initialization block?

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialise the common part of various constructors of a class. The order of initialization constructors and initializer block doesn't matter, initializer block is always executed before constructor.

How do you initialize an object?

To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.

How do you initialize an object in C++?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

What are initializers in Java?

In Java, an initializer is a block of code that has no associated name or data type and is placed outside of any method, constructor, or another block of code. Java offers two types of initializers, static and instance initializers.


1 Answers

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:

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>
like image 78
Stefan Avatar answered Oct 17 '22 02:10

Stefan