From: Intransition Date: 2010-06-20T00:34:14+09:00 Subject: Re: General Ruby OOP question On Jun 19, 9:56 am, "Paul A." wrote: > Hello, > > I have a general question about OOP with Ruby.  If I have 2 class: Home > and Person for instance, such as: > > >> class Home > >>   def initialize > >>     @person1 = Person.new > >>     @person2 = Person.new > >>     # ... > >>   end > > >>   def open_a_window; end > >>   # ... > >> end > >> class Person > >>   def play_wii_game; end > >> end > > Then, a home instance can include a lot of people. And that's cool.  And > a home instance can apply action on a person using a method just like: > @person2.play_wii_game > > But if a person want to open a window in its home?  Here, with a such > design it's impossible, isn't it. > > So to allow this kind of action, I think we need to pass as parameter > self inside Home initialization process, becoming: > > > > >> class Home > >>   def initialize > >>     @person1 = Person.new(self) > >>     @person2 = Person.new(self) > >>     # ... > >>   end > > >>   def open_a_window; end > >>   # ... > >> end > >> class Person > >>   def initialize(home) > >>     @home = home > >>   end > > >>   def open_a_window > >>     @home.open_a_window > >>   end > > >>   def play_wii_game; end > >> end > > Now, a instantiated person can do it using open_a_window proxy method. > And any other proxifyable home's methods. > > But is it ethics? I mean, is that lawful under the principles of > object-oriented programming. Maybe this is so much power, to pass self > inside person instance inside its home... 'cause it's almost as if there > was no class, no partitioning. > > What do you think about this? > Thanks for any considerations. It's fine. But why is Home creating people? Perhaps they should be added to a home? In which case you could create a home and then a person with a home and the person would be automatically added to that home. home = Home.new person1 = Person.new(home1) Or you could create both the home and person separately but when you add the person to the home they will pick up a reference to it. home = Home.new person1 = Person.new home << person1 In Home: class Home def <<(person) @persons << person person.home = self end ~trans