为什么我不能在单例类定义中使用类实例变量?

我正在尝试在单例类中设置一个实例变量,我无法让它工作。

这是问题的简化版本:

class MyClass class << self attr :my_attr @my_attr = {} def my_method (x, y) (@my_attr[x] ||= []) < NoMethodError: undefined method `[]' for nil:NilClass 

这是原始代码示例:

 class Mic class Req < Rack::Request; end class Res < Rack::Response; end class << self attr :routes @routes = {} def call(env) dup.call!(env) end def call!(env) (@app||=new).call(env) end def get(path, opts={}, &blk) puts @routes.inspect # nil route 'GET', path, opts, &blk end def route(type, path, opts, &blk) (@routes[type]||=[]) << {type: type, path: path, opts: opts, blk: blk} end end def call(env) @env = env @req = Req.new(env) @res = Res.new @res.finish end end 

所以,缩写代码,但你可能想要的是尽可能避免访问实例变量。

 class Mic class << self def routes @routes ||= {} end def method_which_acccess_routes routes[:this] = :that end end def instance_method_access_routes Mic.routes[:the_other] = :nope end end 

您可以在没有访问器的情况下以这种方式修改路由,但是如果您需要完全覆盖它,那么您还需要一个attr_writer方法用于routes