From: Daniel Schierbeck Date: 2006-11-23T22:35:53+09:00 Subject: Re: Rubyish inst.var initializations On Thu, 2006-11-23 at 10:04 +0900, Victor "Zverok" Shepelev wrote: > Hi all. > > I have some huge class with aspects of functionality spreaded in several > source files. > > And in some of those aspects there is the same picture: > --- > class MyClass > def push_something(obj) > @something_list ||= [] > @something_list << obj > end > > def use_something(i) > (@something_list ||= [])[i] > end > end > --- > > Then I note (through profiler) various push_XXX spend too much time in > checking is @XXX_list initialized. Then I change it: > > --- > class MyClass > alias :initialize_without_something :initialize > > def initialize(*arg) > initialize_without_something(*arg) > @something_list = [] > end > > def push_something(obj) > @something_list << obj > end > > def use_something(i) > @something_list[i] > end > end > --- > > Now push_XXX and use_XXX work cleaner and faster, but all those initialize > aliases (now I have 5 or 6) don't seem to be very elegant. > > Is there better solution? > > (to be clear, all those push_XXX are NOT similar - some of them push object > to hashes, others to arrays, params count differ and so on - so, they can't > be generated at once through metaprogramming) class MyClass def something_list @something_list ||= [] end def push_something(obj) something_list << obj end end Optionally you could make #something_list private if you don't wish to expose it to the outside. Cheers, Daniel