I cannot determine the correct block initialization
class Foo attr_accessor :bar end obj = Foo.new do |a| a.bar = "baz" end puts obj.bar
Expect "baz" instead get nil
What is the correct spell for block class initializers in ruby?
Try again:
class Foo attr_accessor :bar end obj = Foo.new.tap do |a| a.bar = "baz" end puts obj.bar
Another way to make a block initializer is to write it yourself:
class Foo attr_accessor :bar def initialize yield self if block_given? end end
And later use it:
foo = Foo.new do |f| f.bar = true end
My two cents.
I don't think new can take a block. Never seen him anyway. Why do you want to initialize a block? You can always do obj = foo.new.tap do |a| ... obj = foo.new.tap do |a| ... if you really need a block
new
obj = foo.new.tap do |a| ...
in fact, you have a constructor for these purposes:
class Foo attr_accessor :bar def initialize(bar = "baz") @bar = bar end end