Robert Klemme
4/20/2008 10:05:00 PM
On 20.04.2008 23:37, Chad Murphy wrote:
> Here is what I'm trying to do
>
> class List
> # Method item
> # Pushes an item into an array @items
> # Method to_s
> # returns elements within @items into a string
> end
>
> class Groceries < List
> item :lettuce
> item :potato
> item :ham
> end
>
> print Groceries.new
>
> The trouble I'm having is figuring out how to go about adding an
> instance variable, which is an array, and will be updated using these
> attr like methods (I don't know what these are called which is giving me
> some trouble).
You are looking for class methods.
> Is this possible to pull off?
Yes, but I doubt it is what you want: you are asking for class methods
to add items but you create an instance (Groceries.new). Where is the
point in defining a list of items on class level and instantiate it
multiple times?
If you describe what you want to achieve, i.e. what (business) problem
you are trying to solve we can come up with other suggestions that may
be more appropriate.
For example: this looks like a case for inheritance:
class Grocery
end
class Lettuce < Grocery
end
class Potato < Grocery
end
....
With a little bit of meta programming you can then get all the
subclasses of Grocery.
Kind regards
robert