Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize class in block in Ruby?

Tags:

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?

like image 636
Doug Avatar asked Mar 22 '12 16:03

Doug


3 Answers

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.

like image 120
rscarvalho Avatar answered Nov 01 '22 08:11

rscarvalho


Try again:

class Foo 
  attr_accessor :bar
end

obj = Foo.new.tap do |a|
  a.bar = "baz"
end

puts obj.bar
like image 25
Reactormonk Avatar answered Nov 01 '22 07:11

Reactormonk


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

like image 2
ksol Avatar answered Nov 01 '22 08:11

ksol