Doug
Doug

Reputation: 15553

How to initialize class in block in Ruby?

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

Answers (4)

ksol
ksol

Reputation: 12275

I don't think new can take a block. Never saw it anywhere anyway. Why do you want to initialize in a block ? You can always do obj = foo.new.tap do |a| ... If you really want a block

Upvotes: 2

rscarvalho
rscarvalho

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

Reactormonk
Reactormonk

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

Sergey
Sergey

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

Related Questions