[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Creating objects from a template

e

2/9/2005 6:51:00 AM


>
> Lähettäjä: "David McCabe" <davemccabe@gmail.com>
> Aihe: Creating objects from a template
>
> Hi folks.
>
> I'm pretty comfortable with Python, and I just decided to give Ruby a
> shot. I'm trying to duplicate a nifty method I use in Python to
> instantiate objects with properties that are loaded from a file.
>
> My program is a war strategy game, which involves several different
> types of artillery units. Each type has properties such as range,
> speed, power, etc. I need to load these values from a file.
>
> In python, my parser returns a hash of unit_type objects, where the
> names of units are the keys. Each time a unit is instantiated, it
> receives a unit_type object as an argument. Now here's the interesting
> part: it copies the instance variables from the unit_type into itself.
>
> class Unit(object):
> def __init__(self, type):
> self.type = type
> self.__dict__.update(self.type.__dict__)
>
> There's more to it than that, but that's the interesting part. So now
> I can say:
>
> my_new_unit = Unit(types["Panzer"])
>
> And I'll get a Unit object with all the values for Panzers
> initialized.
>
> drbrain on #ruby-lang came up with this:
>
> http://rafb.net/paste/results/lgb...
>
> It looks like it'll do what I want. There's only one deficiency: I
> would have to list out every possible proporty of a unit in two
> seperate places in the source. In the python version, I don't have to
> list it at all. Whatever properties are in the config file are loaded
> into the object.
>
> So, now I'm looking for any pointers on ways to do this.

Well, a *really* simple solution would be this:

class Object
def steal_ivs(other)
other.instance_variables.each do |iv|
self.instance_variable_set(iv, other.instance_variable_get(iv))
end
end
end

I'll leave the elegant stuff to the gurus.

> Thanks!

E