From: Julian Snitow Date: 2003-05-27T15:24:34+09:00 Subject: Re: Constant Definitions and Hiding On Mon, 26 May 2003 21:58:48 +0200, Robert wrote: > > Hi, > > we had a discussion on #irc the minute before and I'm thinking that there > ought to be a warning in this situation: > > class Foo > BAR = "bar" > > def print_it > p BAR > end > end > > class Bar < Foo > def print_it > p BAR > end > end > > Foo.new.print_it > Bar.new.print_it > > class Bar < Foo > # next line should IMHO issue a warning > # because of the hidden constant Foo::BAR > BAR = "foo" > end > > Foo.new.print_it > Bar.new.print_it > > Output: > > "bar" > "bar" > "bar" > "foo" > > This code does not warn (at least with 1.6.8) either with or without -w. > > What do others think? > > robert Perhaps using constants inside a class is what ought to be warned. class Foo def bar "bar" end def print_it p bar end end class Bar < Foo def bar "foo" end end In a language that lets you do such beautiful, fluid things with functions, the C++ mindset can only hold you back. ;-) If you must distrust the programmer so much, you can either make bar a class method ( def Foo.bar ), and def print_it; p Foo.bar; end, or, if going the constant route, refer to Foo::BAR explicitly. If you don't specify that you only want the BAR defined in class Foo, and not some subclass's idea of BAR, then the example you posted shows the correct behavior on the part of the ruby interpreter. Remember the line, "A computer never does what you want it to do; only what you tell it."? No amount of warnings will change that. :-) Cheers, Julian