Skip to content

Class variable in subclass is not overtaken by class variable in superclass #1554

@DavidEGrayson

Description

@DavidEGrayson

I was experimenting with class variables and I noticed that JRuby's class variables behave differently than MRI's. If a class variable is defined in a superclass after one of its subclasses already has a class variable of the same name, MRI detects the situation and merges the two variables into one. JRuby does not detect it, and it lets the class variable have a different value in the subclass and parent class.

Here is a simple script to demonstrate the difference:

class A
end

class B < A
  @@cv = :cvb  
  def cvb
    @@cv
  end
end

class A
  @@cv = :cva
end

p B.new.cvb

Here is shell output showing how JRuby prints :cvb:

$ jruby -v test.rb
jruby 1.7.11 (1.9.3p392) 2014-02-24 86339bb on Java HotSpot(TM) 64-Bit Server VM 1.7.0_45-b18 [Windows 8-amd64]
:cvb

Here is shell output showing how MRI prints a warning and then prints :cva:

$ ruby -v test.rb
ruby 2.0.0p0 (2013-02-24) [x64-mingw32]
test.rb:7: warning: class variable @@cv of B is overtaken by A
:cva

(Sorry if this is a duplicate; I searched through the names of all open issues but not closed ones.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions