#607 open
Adam Gardiner

[BUG] Metaclasses and Class variables

Reported by Adam Gardiner | June 15th, 2008 @ 03:08 PM | in 0.11

Class variables created in a metaclass method via SClass/Defn nodes are not created correctly on the class, but are if created via a Defs node.

class Foo
  def self.map1  # Defs
    @@map1 ||= {}
  end

  class << self  # SClass
    def map2     # Defn
      @@map2 ||= {}
    end
  end

  map1[:a][:b] = 1  # works fine
  map2[:a][:b] = 1  # raises NoMethodError []= on NilClass
end

The bytecode generated for map1 and map2 is identical, but the staticscopes are different, suggesting this is the cause of the problem.

Comments and changes to this ticket

  • pluskid

    pluskid June 16th, 2008 @ 12:42 AM

    The code will fail on line 12 (map1[:a][:b] = 1) for me on both Ruby 1.8 and Rubinius. I'm not sure if I understood what you mean. But if I change the code from map1[][] = 1 to @map1[:a] = 1@, it will pass for both Ruby 1.8 and Rubinius.

  • Adam Gardiner

    Adam Gardiner June 16th, 2008 @ 02:21 PM

    Oops! This was a simplified example drawn from real code (rdebug), and when it gave the same error, I assumed it was correctly showing the problem in Rubinius...

    The correct test code should be as follows:

    class Foo
      def self.map1  # Defs
        @@map1 ||= {}
      end
    
      class << self  # SClass
        def map2     # Defn
          @@map2 ||= {}
        end
      end
    
      # Initialise the cvars
      map1[:a] ||= {}   
      map2[:a] ||= {}
      
      # Now try and use them
      map1[:a][:b] = 1  # works fine
      map2[:a][:b] = 1  # raises NoMethodError []= on NilClass
    end
    

    This will work fine on MRI, but the final assignment to map2 will fail on Rubinius.

  • Wilson Bilkovich

    Wilson Bilkovich June 25th, 2008 @ 10:20 AM

    • → Tag changed from “” to “bug”
    • → Milestone changed from “1.0 preview” to “0.10”
    • → State changed from “new” to “open”
  • Wilson Bilkovich

    Wilson Bilkovich July 10th, 2008 @ 03:37 PM

    • → Milestone changed from “0.10” to “0.11”

Please Login or create a free account to add a new comment.

You can update this ticket by sending an email to from your email client. (help)

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Tags