Reputation: 15553
I can't figure out the proper block initialize
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 proper incantation for block class initializers in ruby?
Upvotes: 7
Views: 5711
Reputation: 12275
I don't think Never saw it anywhere anyway. Why do you want to initialize in a block ? You can always do new
can take a block.obj = foo.new.tap do |a| ...
If you really want a block
Upvotes: 2
Reputation: 552
Another way to make a block initializer would be writing it yourself one:
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.
Upvotes: 30
Reputation: 21740
Try again:
class Foo
attr_accessor :bar
end
obj = Foo.new.tap do |a|
a.bar = "baz"
end
puts obj.bar
Upvotes: 9
Reputation: 11928
actually you have a constructor for these purposes:
class Foo
attr_accessor :bar
def initialize(bar = "baz")
@bar = bar
end
end
Upvotes: 0