Issue #11022 has been updated by jeremyevans0 (Jeremy Evans).


This issue is not specific to opening a singleton class (`class <<`), but applies to any case where the class being opened is a singleton class.  You get the same output for:

```ruby
module Mod1
  O = Object.new.singleton_class
  class O
    C = 1
    @@cv = 1
    p Module.nesting,
      constants(false),
      class_variables(false),
      Mod1.class_variables(false)
  end
end
```

This explains why it works for `nil` (and presumably `true` and `false`):

```ruby
module Mod1
  class << nil
    C = 1
    @@cv = 1
    p Module.nesting,
      constants(false),
      class_variables(false),
      Mod1.class_variables(false)
  end
end
# [NilClass, Mod1]
# [:C]
# [:@@cv]
# []
```

I'm not sure if this class variable behavior is a bug or spec.  If you consider it a bug, and say that class variables set inside a singleton class definition are set on the singleton class and not the outer nesting, then you would probably break the following code (and I'm guessing `class << self` is much more common than `class << some_other_object`):

```ruby
module Mod1
  class << self
    @@cv = 1
  end

  def a
    @@cv
  end
end
```

FWIW, Ruby does allow you to set class variables on singleton classes via `class_variable_get`/`class_variable_set`, but you cannot access them via normal means:

```ruby
module Mod1
  singleton_class.class_variable_set(:@@cv, 1)

  class << self
    p class_variable_get(:@@cv)
    @@cv
  end
end
# 1
# NameError: uninitialized class variable @@cv in Mod1
```

----------------------------------------
Bug #11022: opening an eigenclass does not change the class variable definition context
https://bugs.ruby-lang.org/issues/11022#change-79176

* Author: bughit (bug hit)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: ruby 2.2.1p85 (2015-02-26 revision 49769) [i686-linux]
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN, 2.2: UNKNOWN
----------------------------------------
```ruby
module Mod1

  class << Object.new

    C = 1
    @@cv = 1

    p Module.nesting,
      constants(false),
      class_variables(false),
      Mod1.class_variables(false)

  end

end
```
```
[#<Class:#<Object:0xb6913d98>>, Mod1]
[:C]
[]
[:@@cv]
```

Shouldn't class var resolution be relative to the current lexical class (Module.nexting.first)?





-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>