From: Robert Klemme Date: 2004-08-22T19:40:45+09:00 Subject: Re: Callback for instance var creation? "T. Onoma" schrieb im Newsbeitrag news:200408212304.28814.transami@runbox.com... > Is there a callback for when an instance variable is first used? I know they > are "instantiated" upon use and set to nil. No, they are instantiated on first assignment: >> class Foo;end => nil >> f=Foo.new => # >> f.instance_eval { puts @bar } nil => nil >> f => # >> f.instance_variables => [] >> f.instance_eval { @bar = "yes" } => "yes" >> f => # >> f.instance_variables => ["@bar"] > I would like to set this to > something else dependent on the name of the variable. Which problem are you trying to solve? Usually attribute accessors can do what you want. class Foo attr_accessor :bar def bar=(b) @bar = "foo #{b}" end end >> f=Foo.new => # >> f.bar = "bar" => "bar" >> f.bar => "foo bar" >> f => # >> Other than that if you need to intercept all variable settings a modified Hash might be better for managing your instance vars: class Foo class FooHash < Hash def []=(k,v) case k when :foo super(k, "bar #{v}") else super end end end def initialize @vars = FooHash.new end def method_missing(sym, *args, &b) case sym.to_s when /^(\w+)=$/ @vars[$1.intern] = args[0] when /^(\w+)$/ @vars[sym] else super end end end >> f=Foo.new => # >> f.foo = 10 => 10 >> f.bar = 20 => 20 >> f => #20, :foo=>"bar 10"}> >> This of course is just an example. It depends on the real problem at hand that you are trying to solve. Regards robert