我正在研究RoR课程并且在irb控制台中收到错误: " NameError:InstanceCounter中的未初始化的类变量@@实例:: InstanceMethods"
我需要在modules.rb中更改什么?
控制台:
Evgenys-MacBook-Pro-2:lesson_05 admin$ irb
2.3.1 :001 > load 'modules.rb'
=> true
2.3.1 :002 > load 'car.rb'
=> true
2.3.1 :003 > car=Car.new
initialize
NameError: uninitialized class variable @@instances in InstanceCounter::InstanceMethods
Did you mean? instance_methods
from modules.rb:35:in `initialize'
from (irb):3:in `new'
from (irb):3
from /Users/aku/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'
modules.rb:
module InstanceCounter
module ClassMethods
@@instances = 0
def instances
puts "@@instances"
@@instances
end
end
module InstanceMethods
def initialize
puts "initialize"
register_instance
super
end
protected
def register_instance
@@instances += 1
puts "@@instances += 1"
end
end
def self.included(base)
base.extend ClassMethods
base.send :prepend, InstanceMethods
end
end
car.rb:
class Car
include InstanceCounter
def initialize
puts "initialize2"
end
end
class PassengerCar < Car
end
class CargoCar < Car
end