From: daz Date: 2005-11-01T02:02:07+09:00 Subject: Re: City and Connection draq wrote: > E. g. I am going to make a programm for a forwarding agency containing > two classes: City and Connection. > > The class City contains information about clients, goods etc. and the > class Connection implies the path length, potential toll charges and > type of the road. > > How can I implement the two classes the best? With both classes > referring to each other? > In my inexperience, I would inherit from a Map. Fortunately for you, there are folks here who'll tell us why this is an awful suggestion (?) ;-) class Map Cities = Hash[] def Map.add_city(name, latitude, longitude) Cities[name] = City.new(name, latitude, longitude) end end class City < Map attr_reader :grid_ref, :name def initialize(name, latitude, longitude, *rest) @name = name @grid_ref = [latitude, longitude] end end class Connection < Map attr_reader :conn1, :conn2, :distance def initialize(name1, name2) @conn1 = Cities[name1] @conn2 = Cities[name2] @distance = 'some calculation' end end Map.add_city('Tokyo', 33, 11) Map.add_city('Paris', 44, 22) Map.add_city('Melbourne', 11, 88) Map.add_city('New Delhi', 00, 77) Map.add_city('Singapore', 55, 55) c01 = Connection.new('Tokyo', 'Paris') p [c01.conn1.name, c01.conn1.grid_ref] # ["Tokyo", [33, 11]] (don't take this too seriously, yet) daz