As mentioned
earlier, everything in Ruby is an instance of a Class. Every Ruby object has a series of ancestors.
The singleton class is an anonymous class specific to an instance. That means that ultimately,
every instance in a Ruby system could have its own singleton class. That??™s also what allows us to
do something like this:
a = Object.new
def a.hello
puts "Hello"
end
a.hello
APPENDIX A ?– RUBY FOR JAVA PROGRAMMERS 298
The hello method is defined on the singleton class of the instance called a. No other class or
object in Ruby has this method. But what is interesting about the singleton class is that classes in
Ruby also can have a singleton class, because they are regular instances. Now, a class such as
String is an instance of Class. However, you can define new methods on the String object,
which isn??™t available on the Class class. These methods are available on the singleton class of
the String object. If you think about it, that??™s what allows you to create something similar to
static methods in Java like this:
class String
def self.hello
puts "Hello from the String singleton class"
end
end
String.hello
The difference is, in Ruby there??™s only one single type of method. There??™s nothing strange
or static about these methods; they??™re just defined on the singleton class instead of on a regular
class. If you need to get a reference to the singleton class of an object, this code will achieve
it for you:
class Object
def singleton_class
(class <
end
end
Now you can invoke the method singleton_class on any object in Ruby and get back a
reference to that class.
Pages:
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436