2014-01-12

[Ruby] use self.class to override the constants in the subclasses

In Ruby names starting with uppercase letters are constants.  When you use a reference to a constant in a method, that refers to the constant defined in the class.  If you make a subclass, the method was inherited to the subclass, but the constant is still resolved against the superclass where the method was originally defined in.

If that is undesirable, we can use "self.class::NAME" synatax to refer to find the constant defined in the class in which the method is really used.

Tested in Ruby 1.8.5:

$ cat test.rb
class A
  Config = "constant in class A"
  def initialize
    p self.class.name
    p Config
    p self.class::Config
  end
end

class B < A
  Config = "constant in class B"
end

A.new
B.new
$ ruby test.rb
"A"
"constant in class A"
"constant in class A"
"B"
"constant in class A"
"constant in class B"

No comments :

Post a Comment