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
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With