From: Robert Klemme Date: 2005-01-02T19:11:38+09:00 Subject: Re: Inheritance of class variables "darren" schrieb im Newsbeitrag news:200501011014.19101.rubylang@usmstudent.com... >I think I understand all of the code in this thread (see below) except for >the > 2nd line "attr_reader :name, :total_of_cars". Could you, or someone, > explain > this line to me, please? > > Also, I tried putting this code into a single *.rb file and I couldn't get > any > output. I did get a few warnings, however: > > ex. > /1foo.rb:4: warning: parenthesize argument(s) for future version > /1foo.rb:7: warning: parenthesize argument(s) for future version > /1foo.rb:8: warning: parenthesize argument(s) for future version > /1foo.rb:12: warning: parenthesize argument(s) for future version > /1foo.rb:12: warning: parenthesize argument(s) for future version > /1foo.rb:13: warning: parenthesize argument(s) for future version > /1foo.rb:4: undefined method ` ' for CarBuilder:Class (NoMethodError) > > I guess the warnings mean that some syntax is being deprecated in later > versions. Assuming that is correct, I still don't see what is generating > the > last error. Which version of Ruby are you using? I tested with 1.8.1 and didn't see any of those errors. Maybe it's a copy and paste problem from the mail? Line endings could be a reason. > So, I tried using irb to enter it line by line. However, when I get down > to > the where I declare the first instance (h = CarBuilder.new "Honda"), irb > gives me the error, "NameError: uninitialized constant CarBuilder". Works for me: $ irbs >> class CarBuilder >> attr_reader :name, :total_of_cars >> ?> def initialize(name) >> @name = name >> @total_of_cars = 0 >> end >> ?> def build >> puts "#{name} builds another car" >> @total_of_cars += 1 >> end >> end => nil >> ?> h = CarBuilder.new "Honda" => # > Finally, I don't see where you are keeping up with the actual total of > cars > built by all manufacturers. My example code doesn't. > So, for practice, I was going to try to extend > this code to handle that. Would the proper way to do that be to declare a > class variable (like @@collective_total = 0) and put it somewhere inside > of > the class (like right after the attr_reader . . . line)? Then, inside of > the > build method, bump the collective_total? I would not use a class var. Rather use an instance var of the class. You could also query all instances which reduces redundancy and thus error likelyness: >> total = 0; ObjectSpace.each_object(CarBuilder) {|o| total += >> o.total_of_cars}; total => 0 >> h.build Honda builds another car => 1 >> h.build Honda builds another car => 2 >> h.build Honda builds another car => 3 >> total = 0; ObjectSpace.each_object(CarBuilder) {|o| total += >> o.total_of_cars}; total => 3 Of course, if you need the number of all cars often then it's more efficient to introduce redundancy and have a total of all car makers available. Regards robert