From: Chris White Date: 2011-08-15T01:50:28+09:00 Subject: Re: class inheritance and class constants On Aug 14, 2011, at 9:31 AM, Iņaki Baz Castillo wrote: > ------------------------ > class A > HELLO = "Hello I'm A" > > def hello > puts HELLO > end > end > > class B < A > HELLO = "Hello I'm B" > > def hello2 > puts HELLO > end > end > ------------------------ > > B.new.hello > => "Hello I'm A" (ouch...) > > B.new.hello2 > => "Hello I'm B" > Correct, since the method is being called in the context of A, it will search starting from A. You can verify this by printing out the Module.nesting value which is used for constant lookup searching: ------------------------- class A HELLO = "Hello I'm A" def hello p Module.nesting puts HELLO end end ------------------------- This will output [A]. > So, if a contstant appears within a method, its value is evaluated for > the class in which such method is defined ("hello" is defined in class > A not in B, so it takes HELLO from class A). > I don't like this behavior (just my opinion). Do I miss something? This behavior can fortunately be overridden by simply overriding the hello method in the B class, meaning that it will use the constant defined in B instead: -------------------------- class A HELLO = "Hello I'm A" def hello puts HELLO end end class B < A HELLO = "Hello I'm B" def hello puts HELLO end def hello2 puts HELLO end end B.new.hello -------------------------- Regards, Chris White http://www.twitter.com/cwgem