Robert Dober
5/2/2007 6:49:00 PM
On 5/2/07, Ball, Donald A Jr (Library) <donald.ball@nashville.gov> wrote:
> Okay, so maybe this turns out to be a not-so-simple subclass question
> after all. I appreciate all the thoughtful answers and links, I'm pretty
> close to wrapping my head around it all. I'm still having trouble with
> class instance variable initialization, and have come up with code
> sample which should illustrate the point:
>
> class Breakfast
> def self.add_food(*args)
> @foods ||= []
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
......
<snip>
> Everybody loves breakfast, right? This code works great, except... maybe
> I don't want Breakfast to have :eggs by default, but if I remove the
> add_food :eggs from Breakfast, then Breakfast.foods returns nil instead
> of [] since @foods isn't initialized until add_food is called, and
> RubyBreakfast.foods throws an exception trying to its delicious foods
> array to nil. But I'll be damned if I can figure out how to properly
> initialize @foods in Breakfast. Can someone point me in the proper
> direction?
Hopefully I did, if not continue asking I am a bad teacher, I know :(.
(1)
class A
@cl_inst_var = 42
end
is the same (unless class A has been defined before) as
A = Class.new { @cl_inst_var = 42 }
Cheers
Robert
--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw