On 5/2/07, Ball, Donald A Jr (Library) <donald.ball / nashville.gov> wrote:
> > just initialize @foods in the class
> >
> > class Breakfast
> >     @foods = []  # class instance variable, I did this in my
> > original example
> >                          # because of (1)
> >     def self.add_food( *args)
> >           @foods += args
> >     end
> >
> >     ......
>
> but then @foods doesn't exist in RubyBreakfast and BoringBreakfast. I
> mean, sure, I could cut'n'paste @foods = [] in each of them, but that
> doesn't smell right. In the superclass, I want a chunk of code that
> initializes a class instance variable in itself and each of its class
> descendents.
You mean you want to have your cake *and* eat it ;)?
Sure enough, but there is no simple solution, you could do something like this

class Module
    def inherit_cl_inst_vars  # refinement via args as you wish
        superclass.instance_variables.each do
             | ivar |
             instance_variable_set ivar,
superclass.instance_variable_get( ivar )
        end
    end
end

class A
  @a = 42
end

class B < A
  inherit_cl_inst_vars
end

class << A
  attr_accessor :a
end

puts A.a
puts B.a
B.a=1764
puts A.a
puts B.a
>
> In point of fact, I can work around the @foods.nil? case in the
> self.foods method, but I'd rather figure out either how to do this or
> why it's a bad idea to do it. :)
>
> - donald
>
>

Robert
-- 
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw