News for hackers. Stuff that matters.
Re:Strangest Language Features by judofyr on Thursday December 15, 2011 @01:50PM (#3357376)
Another one: class variables!

    # Define two class variables in two different classes:
    class MyClass
      @@base = 1
    end
    
    class OtherClass
      @@base = 2
    end
    
    # Define it in the superclass too:
    class Object
      @@base = 3
    end

    class MyClass
      # Magic! The subclass-variable has now changed!
      p @@base # => 3
    end

    class OtherClass
      # In both classes in fact:
      p @@base # => 3
      
      # And finally, let's reset this:
      @@base = 4
    end

    class Object
      # Whoops, this changes the superclass too:
      p @@base # => 4
    end
Explanation: Two class variables with the same name can't exists in the same class hierachy. Therefore, class variable lookup (and setter) will always traverse to the upmost-class where the variable is defined.

(Hope you don't mind that I wrote these in two different posts.)

There are no comments on this comment yet.