From: Robert Klemme Date: 2004-02-01T20:09:52+09:00 Subject: Re: check whether a class is defined, listing all classes "David Garamond" schrieb im Newsbeitrag news:401CC702.9030908@zara.6.isreserved.com... > Given a string of fully-qualified class name, how do I easily check > whether the class is defined or not? I hope it's not as 'hard' as I think: > > def class_defined?(classname) > m = Class > classname.split("::").each { |c| > m.constants.include?(c) or return false > m = m.const_get c > } > return true > end > > p class_defined?("Test::Unit::TestCase") # false > require 'test/unit/testcase' > p class_defined?("Test::Unit::TestCase") # true > > Is there an easier way? irb(main):009:0> defined? Test::Unit::TestCase => nil irb(main):010:0> require 'test/unit/testcase' => true irb(main):011:0> defined? Test::Unit::TestCase => "constant" irb(main):012:0> > A bonus question, how do I list all the defined classes in their fully > qualified name? Example output: > > Object > String > FalseClass > Struct > Struct::Tms > File > File::Stat > ... > > (My own code is very ugly, I'm embarrassed to show it :-) ObjectSpace.each_object( Class ){|cl| p cl} ObjectSpace.each_object( Class ){|cl| p cl.name} Regards robert