From: Robert Klemme Date: 2004-08-23T16:41:14+09:00 Subject: Re: Callback for instance var creation? "T. Onoma" schrieb im Newsbeitrag news:200408221316.47855.transami@runbox.com... > On Sunday 22 August 2004 06:40 am, Robert Klemme wrote: > > > are "instantiated" upon use and set to nil. > > > > No, they are instantiated on first assignment: > > >> class Foo;end > > Oh! I didn't realize b/c if you assign from one that doesn't exist, it returns > nil. > > irb(main):001:0> x=@x > => nil > irb(main):002:0> p x > nil > => nil > > > > 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. > > Actually, its esoteric. I've been thinking about methods as 1st class objects. Methods *are* first class objects: >> class Foo; def bar;end ;end => nil >> Foo.instance_method :bar => # >> Foo.new.method :bar => # And similar to functional languages, functions are also first class objects and you can work functional style in Ruby, too: >> plus = lambda {|a, b| a + b} => # >> plus[ 1, 2 ] => 3 >> curry = lambda {|f, *args| lambda {|*x| f.call(*(args + x))} } => # >> plus5 = curry[ plus, 5 ] => # >> plus5[ 10 ] => 15 > At one point I have suggested that constants be used. See: > > http://www.rubygarden.org/ruby?FirstClassMethods > > But constants are class-level while methods are actually instance level > (strangely enough). Not necessarily, see the first code example above (UnboundMethod). Note also that you can convert between the two types: >> Foo.new.method( :bar ).unbind => # >> Foo.instance_method( :bar ).bind( Foo.new ) => # > So I thought if they were instance level perhaps an > instance variable would be better. Using the capitalization idea from before, > something like: > > def ameth(x) > puts x > end > > p @Ameth # => # > > So I was trying to auto-assign @Ameth. > > > Other than that if you need to intercept all variable settings a modified > > Hash might be better for managing your instance vars: > > Perhaps something like that would be better. I'll give it some thought. It seems the easiest to do would be to include a Hash for method instances if you want to maintain state: class Object alias :old_method :method def method(s) ( @methods ||= {} )[s] ||= old_method(s) end end >> class Foo >> def bar;end >> end => nil >> f= Foo.new => # >> f.method( :bar ).id => 135011952 >> f.method( :bar ).id => 135004308 >> class Object >> alias :old_method :method >> def method(s) >> ( @methods ||= {} )[s] ||= old_method(s) >> end >> end => nil >> f.method( :bar ).id => 134638968 >> f.method( :bar ).id => 134638968 Kind regards robert