From: "David A. Black" Date: 2004-02-15T00:40:32+09:00 Subject: Re: accessing constants from class methods Hi -- On Sat, 14 Feb 2004, Ara.T.Howard wrote: > On Sat, 14 Feb 2004, daz wrote: > > > Date: Sat, 14 Feb 2004 08:24:08 -0000 > > From: daz > > Newsgroups: comp.lang.ruby > > Subject: Re: accessing constants from class methods > > > > > > "Ara.T.Howard" wrote: > > > > > > what i would like to accomplish would be something like this: > > > > > > > > > class Abstract > > > class << self > > > def x > > > # defined?(self::X) ? self::X : nil > > > end > > > end > > > end > > > > > > class Concrete < Abstract > > > X = 42 > > > end > > > > > > # p Base.x # => nil > > > # p Derived.x # => 42 > > > > > > > > > does this make sense? in essence i want an abstract class method with the > > > semantics of "iff a concrete class has defined a certain constant, return it" > > > > > > the problem is that 'self::X' above tries to reference 'Class::X', if i > > > replace 'self' with 'Abstract' then i will be referencing the incorrect 'X'... > > > > > > how does one say 'the constant of the current class' from within a class > > > method? > > > > > > > #----- > > > > class A > > class << self > > def x > > const_defined?(:X) ? const_get(:X) : nil > > end > > end > > end > > > > class C < A > > X = 42 > > end > > > > p A.x # => nil > > p C.x # => 42 > > > > #----- > > > > > > daz > > perfect! OK, it's probably something simple but I'm staring and staring at the original code, and its output (which is the same as daz's code), and I can't figure out why it wasn't OK. Explanations welcome :-) David -- David A. Black dblack@wobblini.net