RubyのクラスはClassクラスのインスタンスらしい。なるほど。
つまり、以下のようにABCクラスを作るとClassクラスのインスタンスが生成されるらしい。
1 2 3 4 | Class ABC end ABC . class => Class |
そして、クラス名は定数なのだそうだ。上の場合だと”ABC”は定数でもあるらしい(だから、クラス名の最初は大文字)。Classクラスのインスタンスを定数ABCに代入しているということらしい。
上でクラスの作成は以下のように書くこともできる。
1 | ABC = Class . new { } |
より定数に代入しているっぽいですね。
ならば、このクラス名の定数”ABC”はどこのクラスで定義されているのだろうかと。
ちょっと調べたら簡単にわかりました。以下のようにObjectクラスの定数としてクラス名は定義されているようです。
1 2 | p Object .constants.grep / ABC / ⇒ [ "ABC" ] |
Rubyのその他の組み込みクラスのクラス名もObjectクラスに定数として定義されています。さきほど私が定義したクラス名ABCも含めて。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | p Object .constants => [ "ThreadError" , "RUBY_PLATFORM" , "Regexp" , "Deprecate" , "Numeric" , "String" , "SLex" , "Bignum" , "IndexError" , "SecurityError" , "UnboundMethod" , "Exception" , "Readline" , "RubyLex" , "NoMethodError" , "FALSE" , "Object" , "RELEASE_DATE" , "IRB" , "Range" , "IO" , "Integer" , "Config" , "TypeError" , "RubyToken" , "Dir" , "RUBY_VERSION" , "ZeroDivisionError" , "Gem" , "SystemExit" , "NotImplementedError" , "Hash" , "RegexpError" , "Kernel" , "TOPLEVEL_BINDING" , "RUBY_COPYRIGHT" , "GC" , "TRUE" , "STDOUT" , "LocalJumpError" , "Binding" , "Interrupt" , "RUBY_FRAMEWORK" , "ObjectSpace" , "SyntaxError" , "Marshal" , "Enumerable" , "Struct" , "Class" , "Continuation" , "IOError" , "MAXHISTSIZE" , "RangeError" , "Kconv" , "Data" , "Thread" , "RUBY_PATCHLEVEL" , "SystemStackError" , "Array" , "NoMemoryError" , "FileTest" , "MatchData" , "ARGF" , "ETC_IRBRC_LOADED" , "NIL" , "Comparable" , "PLATFORM" , "ArgumentError" , "Float" , "FloatDomainError" , "RUBY_RELEASE_DATE" , "RuntimeError" , "Precision" , "ThreadGroup" , "Signal" , "Fixnum" , "STDERR" , "FalseClass" , "VERSION" , "Exception2MessageMapper" , "RbConfig" , "Errno" , "StandardError" , "Math" , "EOFError" , "LoadError" , "NKF" , "RUBY_FRAMEWORK_VERSION" , "APPLE_GEM_HOME" , "STDIN" , "TrueClass" , "NameError" , "NilClass" , "Process" , "Proc" , "RUBY_DESCRIPTION" , "ARGV" , "ABC" , "SystemCallError" , "SignalException" , "MatchingData" , "File" , "Time" , "ENV" , "ScriptError" , "Symbol" , "Module" , "Method" , "StopIteration" , "DTracer" , "CROSS_COMPILING" , "HISTFILE" ] |
なるほど。なるほど。なるほど。