From: Michael Guterl Date: 2008-08-02T12:48:30+09:00 Subject: Re: Ruby block: why doesn't this work? On Fri, Aug 1, 2008 at 11:04 PM, markbuckingham@gmail.com wrote: > I'm trying to figure out why my code isn't doing what I think it > should... > > Basically, I'm trying to create a Info object, and do various things > to that new object within the block. For what ever reason though, it > doesn't look like the code inside the block is getting executed at > all. (I'm trying to do something that looks kind of like > activerecord's create_table method.) > > So... with the print statements in the code, I'd expect to see output > from the address() and city() methods, but only the initialize method > prints anything. (I can even put complete nonsense in the address or > city methods, and nothing happens.) > > What am I doing wrong? > You need to make the info method call the block. See the code below. > Thanks! > > class Info > attr_accessor :name, :address, :city > > def initialize(name) > @name = name > print "name: #{name}\n" > end > > def address(value) > @address = value > print "address: #{address}\n" > end > > def city(value) > @city = value > print "city: #{city}\n" > end > end > > def info(name) i = Info.new(name) yield i i > end > > info :Bob do |i| > i.address "123 Main St." > i.city "Boston, MA" > end > Also this code will currently give you errors because attr_accessor is overwriting your existing method definitions. I recommend using the 'fattr' gem it will give you most of the functionality you desire. HTH, Michael Guterl require 'rubygems' require 'fattr' class Info fattr :name, :address, :city def initialize(name) self.name = name end end def info(name) i = Info.new(name) yield i i end bob = info 'bob' do |i| i.address "123 foo lane" i.city "oz" end puts bob.inspect