From: Caleb Clausen Date: 2010-06-07T22:52:13+09:00 Subject: Re: Singleton classes and Namespce On 6/7/10, Robert Klemme wrote: > 2010/6/6 Intransition : >> Do singleton classes not get the same namespace treatment as normal >> classes? > > I think so. > >> module M >> class X; end >> end >> >> o = Object.new >> => # >> >> (class << o; self; end).class_eval{ include M } >> => # >> >> def o.x; X; end > > This cannot work since X is not statically in scope. Ah, but constant lookup is supposed to check the ancestors if the constant is not found in the scope. M should be among the ancestors of o's singleton class, shouldn't it? I would have expected this to work. OTOH, constant lookup is confusing. This way works: module M class X; end end o = Object.new # => # (class << o; self; end).class_eval{ include M } # => # #or o.extend M as well, presumably class<M::X See http://ruby.runpaint.org/variables#constants in which the lookup rules are summarized as: (Module.nesting + container.ancestors + Object.ancestors).uniq #slightly paraphrased I guess the key point to understand is that for singleton methods, container is the (static) module of class enclosing the singleton method, NOT the singleton class that they affect.