From: Axel Etzold Date: 2008-05-24T21:52:46+09:00 Subject: Re: How to model something -------- Original-Nachricht -------- > Datum: Sat, 24 May 2008 20:09:51 +0900 > Von: Tobias Weber > An: ruby-talk@ruby-lang.org > Betreff: How to model something > Hi, > my programm needs to store persons. They have a weight and a gender. You > are only allowed to ask males for their weight, females will throw > dishes/exceptions. There *is* a method to change someones gender. > > I could have 'if gender' in every accessor or use the state pattern. But > that has no state, so I'm confused. I would have to access the variable > in the wrapper class. > > The programm can also shoot people into space, in which case the > implementation of weight changes but the same restrictions apply. > The proxy pattern will help here, probably by having weight first call > delegate.weight, and if that isn't NoMethodException multiplying with > gravity. > > Any advice or implementations of similar problems I could look at? > > (and in reality people are TV series with 6 genders and 5 other > attributes, and space is just but a remote place to store things) > > -- > Tobias Weber Hi Tobias, I'd use Struct ... Best regards, Axel ----------------------------------------------------------- Human=Struct.new(:name,:gender,:weight,:position) def check_and_multiply(arg,default_value,factor) # return factor, if arg==default_value, else return 1 if arg==default_value return factor else return 1 end end class Human def ask_for_weight(weight_loss_factor=0.5) if self.gender=='female' return "Don't ask me this!" else return self.weight*check_and_multiply(self.position,'space',weight_loss_factor) end end def change_sex temp=self.dup if self.gender=='male' temp.gender='female' end if self.gender=='female' temp.gender='male' end return temp end def change_position temp=self.dup if self.position=='earth' temp.gender='space' end if self.gender=='space' temp.gender='earth' end return temp end end man1=Human.new('John','male',75.0,'space') man2=Human.new('James','male',75.0,'earth') woman=Human.new('Mary','female',55.0) p woman.ask_for_weight p man1.ask_for_weight p man2.ask_for_weight p man2.change_sex.name ------------------------------------------------------------------ -- GMX startet ShortView.de. Hier findest Du Leute mit Deinen Interessen! Jetzt dabei sein: http://www.shortview.de/?mc=sv_ext_mf@gmx