constants, const_get
Module#constantsで定数の一覧が得られ、Module#const_getで実際の値が得られます。
p Math.constants p Math.const_get("PI") Math.constants.sort.each do |c| puts "#{c} = #{Math.const_get(c)}" end
実行結果です。
["E", "PI"] 3.14159265358979 E = 2.71828182845905 PI = 3.14159265358979
Mathモジュールではなく、Objectモジュールの定数一覧を作ってみましょう。
Object.constants.sort.each do |c| puts "#{c} = #{Object.const_get(c)}" end
実行結果です。
ARGF = ARGF ARGV = ArgumentError = ArgumentError Array = Array Bignum = Bignum Binding = Binding Buffering = Buffering CROSS_COMPILING = Class = Class Comparable = Comparable Config = Config Continuation = Continuation DATA = #<File:0x2947558> Data = Data Date = Date DateTime = DateTime Dir = Dir ENV = ENV EOFError = EOFError Enumerable = Enumerable Errno = Errno Exception = Exception FALSE = false FalseClass = FalseClass Fcntl = Fcntl File = File FileTest = FileTest Fixnum = Fixnum Float = Float FloatDomainError = FloatDomainError Forwardable = Forwardable GC = GC Gem = Gem Hash = Hash IO = IO IOError = IOError IndexError = IndexError Integer = Integer Interrupt = Interrupt Kernel = Kernel LoadError = LoadError LocalJumpError = LocalJumpError Marshal = Marshal MatchData = MatchData MatchingData = MatchData Math = Math Method = Method Module = Module NIL = NameError = NameError NilClass = NilClass NoMemoryError = NoMemoryError NoMethodError = NoMethodError NotImplementedError = NotImplementedError Numeric = Numeric Object = Object ObjectSpace = ObjectSpace OpenSSL = OpenSSL PLATFORM = i386-mswin32 ParseDate = ParseDate Precision = Precision Proc = Proc Process = Process RELEASE_DATE = 2005-12-24 RUBY_PLATFORM = i386-mswin32 RUBY_RELEASE_DATE = 2005-12-24 RUBY_VERSION = 1.8.4 Range = Range RangeError = RangeError Rational = Rational Regexp = Regexp RegexpError = RegexpError RuntimeError = RuntimeError STDERR = #<IO:0x294e740> STDIN = #<IO:0x294e770> STDOUT = #<IO:0x294e758> ScriptError = ScriptError SecurityError = SecurityError Signal = Signal SignalException = SignalException SingleForwardable = SingleForwardable StandardError = StandardError String = String Struct = Struct Symbol = Symbol SyntaxError = SyntaxError SystemCallError = SystemCallError SystemExit = SystemExit SystemStackError = SystemStackError TOPLEVEL_BINDING = #<Binding:0x2947648> TRUE = true Thread = Thread ThreadError = ThreadError ThreadGroup = ThreadGroup Time = Time TrueClass = TrueClass TypeError = TypeError UnboundMethod = UnboundMethod VERSION = 1.8.4 ZeroDivisionError = ZeroDivisionError