From: Joel VanderWerf Date: 2007-06-12T03:37:30+09:00 Subject: Re: Constants and metaclasses Andreas Launila wrote: > Is there a way to define a constant in a metaclass and then have it used > in methods defined in the original class? > > An example: > > > class Foo > def foo > p BAR > end > end > > f = Foo.new > class < BAR = "Hello" > > def bar > p BAR > end > end > > f.bar > f.foo > > > The line "f.bar" will work fine, but "f.foo" will fail with "NameError: > uninitialized constant Foo::BAR". Is there some way to have the method > defined in the original class pick up on the constant in the metaclass > (without altering "p BAR")? > Yes, with a little wrangling: class Object def singleton_class class << self; self; end end end class Foo def foo p self.singleton_class::BAR end end f = Foo.new class <