Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Ruby Programming
Previous Page Home Next Page

Class Names Are Constants

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"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)*args)
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}

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire