Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone please explain class << self to me?

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.

like image 385
Wade Tandy Avatar asked Nov 10 '10 22:11

Wade Tandy


1 Answers

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)
like image 144
Jörg W Mittag Avatar answered Nov 02 '22 13:11

Jörg W Mittag