I'm jumping into rails programming for the first time and while looking at the code for some libraries I've downloaded, I occasionally notice the code:
class << self
def func
stuff
end
end
I've tried searching the web for an explanation, but the << gets stripped from most useful search engines, so it ends up just searching for class self, which isn't very useful. Any insight would be appreciated.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With