NameError on accessing ancestor constants when using Class.new?

Posted by PDG on Stack Overflow See other posts from Stack Overflow or by PDG
Published on 2012-12-09T04:56:22Z Indexed on 2012/12/09 5:04 UTC
Read the original article Hit count: 145

Filed under:
|

To my current knowledge Ruby classes defined with Class.new should not differ from classes created with the class keyword. Then why do following classes B and C behave differently?

class A
  TEST = 'A'   
  def test
    TEST
  end   
end

class B < A
 def test
  TEST
 end    
end

C = Class.new(A) {        
 def test
  TEST
 end    
}

puts 'A: ' + A.new.test # => "A: A"
puts 'B: ' + B.new.test # => "B: A"
puts 'C: ' + C.new.test # => uninitialized constant TEST (NameError)

Tested with ruby 1.9.3p327 and ruby 1.8.7p358.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about nameerror