From: John Feminella Date: 2011-05-08T08:36:40+09:00 Subject: Re: Cross access between instance variables You add fish to a tank, not tanks to a fish. An alternative proposal, that doesn't involve Fish holding a reference to Tanks at all: class Fish # ... def comfortable?(temp_in_degrees_celsius) (@min..@max).include? temp_in_degrees_celsius end end class Tank # ... def add_inhabitant(i) self.inhabitants << i end def update # ... # possible temperature change! self.inhabitants.each do |inhabitant| logger.warn("#{inhabitant} is experiencing environmental stress") unless inhabitant.comfortable?(t) end end end -- John Feminella Principal Consultant, BitsBuilder LI: http://www.linkedin.com/in/johnxf SO: http://stackoverflow.com/users/75170/ On Sat, May 7, 2011 at 19:27, Hassan Schroeder wrote: > 2011/5/7 Stefan Salewski : >> >> Of course this is a way to solve the problem. It may look not very >> natural, that we have to tell the fish the parameters of its tank, when >> we ask the fish about its mood: >> >>>mood =  fish.tell_mood({:temp => t.temp, :food => t.food_type}) >> >> But OK, this is the way to do it. Now I know that I have not missed >> something. > > A little late to this, but isn't this a good case for the Observer pattern? > So the fish are always "aware" of the tank environment? Very simply: > > ----------------------------- > require 'observer' > > class Tank >  include Observable > >  def temperature >    @temperature >  end > >  def temperature=(temperature) >    @temperature = temperature >    changed >    notify_observers(temperature) >  end > > end > > class Fish > >  attr_accessor :tank_temperature > >  def initialize(tank) >    @tank_temperature = tank.temperature >    tank.add_observer(self) >  end > >  def update(temperature) >    puts "temperature changed to #{temperature}" >    @tank_temperature = temperature >  end > > end > ----------------------------- > And exercise with: > ----------------------------- > require 'tank' > require 'fish' > > tank = Tank.new > tank.temperature= 100 > fish = Fish.new(tank) > puts "fish.tank_temperature: #{fish.tank_temperature}"  # => 100 > > tank.temperature= 102 > puts "fish.tank_temperature: #{fish.tank_temperature}" # => 102 > ----------------------------- > > FWIW, > -- > Hassan Schroeder ------------------------ hassan.schroeder@gmail.com > twitter: @hassan > >