From: Robert Klemme Date: 2004-02-16T20:29:55+09:00 Subject: Re: accessing constants from class methods "Ara.T.Howard" schrieb im Newsbeitrag news:Pine.LNX.4.44.0402131650180.4232-100000@fattire.ngdc.noaa.gov... > > 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? Use instance vars of classes: class Class def x ancestors.each do |cl| val = cl.instance_variable_get("@x") return val if val end nil end def x=(val); @x=val; end end class Abstract; end class Concrete < Abstract self.x = 42 end class MostConcrete < Concrete self.x = "forty two" end p Abstract.x p Concrete.x p MostConcrete.x Regards robert