In Ruby, class << foo
opens up the singleton class of the object referenced by foo
. In Ruby, every object has a singleton class associated with it which only has a single instance. This singleton class holds object-specific behavior, i.e. singleton methods.
So, class << self
opens up the singleton class of self
. What exactly self
is, depends on the context you are in, of course. In a module or class definition body, it is the module or class itself, for example.
If all you are using the singleton class for, is defining singleton methods, there is actually a shortcut for that: def foo.bar
.
Here's an example of how to use singleton methods to provide some "procedures" which don't really have any association with a particular instance:
class << (Util = Object.new)
def do_something(n)
# ...
end
end
Util.do_something(n)