From: Gavin Kistner Date: 2006-09-12T08:05:42+09:00 Subject: Re: Reflection and files > Suppose I have a ruby file with a single class. Is it > possible to write a > ruby script that can extract the class name from the file? [...] > Is it possible to extract the class name via reflection? Well, here's one terrible idea. (It's 'terrible' because it's brittle, and only works if no other files defining new classes have been defined, and will break if a new Ruby release defines a new class.) BUILTIN_CLASSES = %w| ArgumentError Array Bignum Binding Class Continuation Data Date DateTime Dir EOFError Exception FalseClass File Fixnum Float FloatDomainError Hash IO IOError IndexError Integer Interrupt LoadError LocalJumpError MatchData MatchData Method Module NameError NilClass NoMemoryError NoMethodError NotImplementedError Numeric Object Proc Range RangeError Rational Regexp RegexpError RuntimeError ScriptError SecurityError SignalException StandardError String Struct Symbol SyntaxError SystemCallError SystemExit SystemStackError Thread ThreadError ThreadGroup Time TrueClass TypeError UnboundMethod ZeroDivisionError |.map{ |n| Object.const_get( n ) } class Foo; end nonstandard_classes = Object.constants.map{ |name| klass = Object.const_get( name ) Class === klass ? klass : nil }.compact - BUILTIN_CLASSES puts nonstandard_classes #=> Foo