We've said that when you invoke a class method, all you're doing is
sending a message to the
Class
object itself. When you say
something such as
String.new("gumby")
, you're sending the message
new
to the object that is class
String
. But how does Ruby
know to do this? After all, the receiver of a message should be an
object reference, which implies that there must be a
constant called ``String'' somewhere containing a reference to the
String
object.
[It will be a constant, not a variable,
because ``String'' starts with an uppercase letter.]
And in fact, that's exactly what happens. All the built-in classes,
along with the classes you define, have a corresponding global
constant with the same name as the class.
This is both straightforward and subtle. The subtlety comes from the
fact that there are actually two things named (for example)
String
in the
system. There's a
constant that references an object of class
String
, and there's the object itself.
The fact that class names are just constants means that you can treat
classes just like any other Ruby object: you can copy them, pass them
to methods, and use them in expressions.
def factory(klass, *args)
|
klass.new(*args)
|
end
|
|
factory(String, "Hello")
|
� |
"Hello"
|
factory(Dir, ".")
|
� |
#<Dir:0x401b51bc>
|
|
flag = true
|
(flag ? Array : Hash)[1, 2, 3, 4]
|
� |
[1, 2, 3, 4]
|
flag = false
|
(flag ? Array : Hash)[1, 2, 3, 4]
|
� |
{1=>2, 3=>4}
|