为什么不能在单例类定义中使用类实例变量? [英] Why can't I use a class instance variable inside a singleton class definition?
本文介绍了为什么不能在单例类定义中使用类实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在单例类中设置实例变量,但无法使其正常工作。
I'm trying to set an instance variable inside a singleton class and I can't get it to work.
这是问题的简化版本:
class MyClass
class << self
attr :my_attr
@my_attr = {}
def my_method (x, y)
(@my_attr[x] ||= []) << y
end
end
end
MyClass.my_method(1, 2)
# => NoMethodError: undefined method `[]' for nil:NilClass
这是原始代码示例:
Here's the original code sample:
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
推荐答案
因此,缩写代码,但是您可能想要避免访问实例变量,因为
So, abbreviated code, but what you probably want is to avoid accessing the instance variable as much as possible.
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
You can modify routes in place this way without an accessor, but if you need to completely overwrite it, you'll need an attr_writer
method for routes
as well.
这篇关于为什么不能在单例类定义中使用类实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文