From: Hugh Sasse Staff Elec Eng Date: 2001-11-28T02:59:08+09:00 Subject: [ruby-talk:26682] Re: adding instance variables to an existing class. On Sat, 24 Nov 2001, MenTaLguY wrote: > > How might I add some instance variables to an existing class, such > > as String, and have them initialized properly? > > Two possibilities come to mind immediately: > > class String > attr_writer :pos > def pos > @pos = 0 if not instance_variables.include? "@pos" > @pos > end > end This didn't work, it still gives me nil, as does David Alan Black's solution of @pos ||= 0. Kent Dahl was right in that I want this to work for all strings, not just those created with an explicit String.new(). > > OR... > > class String > attr_writer :pos > def pos > @pos = 0 > class << self > alias_method :pos, :_pos > end > @pos > end > def _pos ; @pos ; end > end > > That does depend on you always using the accessor, however. That is a price I can pay, but I don't understand what this one is doing -- or at least why it is. I can see it is making a singlton then doing alias then redefine it back, which will set pos to the new method, but why go through the singleton bit? This didn't work either. The codes all blow up where I use a defualt parameter def any(chars, start=@pos, finish=self.length) even if I change this to def any(chars, start=pos, finish=self.length) start always ends up as nil instead of 0. I'm not using the CVS version, I'm using 1.6.4. and I can find no refs to allocate in the RubyCentral reference. > > -mental > Thank you all, a still puzzled Hugh