9

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.

Wade Tandy
  • 4,026
  • 3
  • 23
  • 31
  • 2
    Is google not a useful search engine? http://www.google.com/search?source=ig&hl=en&rlz=&=&q=class+%3C%3C+self&btnG=Google+Search – McKay Nov 10 '10 at 22:26
  • @McKay: Apart from http://forums.pragprog.com/forums/77/topics/657 , which wasn't quite the same as what Wade was doing, which hits were relevant to Wade's question? – Andrew Grimm Nov 10 '10 at 22:35
  • The first two hits are both relevant (the third arguably so). The second link (http://www.thekode.net/blog/blog.html) talks about that idiom specifically and links: http://www.thekode.net/ruby/techniques/DefiningMethodsWithClosures.html which might also be of help. – McKay Nov 10 '10 at 22:40

2 Answers2

12

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)
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • So it's basically the way Ruby handles what would be a static method in a language like Java? Are there any differences? – Wade Tandy Nov 10 '10 at 23:56
  • @Wade - the def portion is like a static method, yes. But you can manipulate class-level variables inside the open class< – Tim Snowhite Mar 21 '11 at 20:24
3

It's the equivalent of

def self.func
  stuff
end

Except that all methods nested in it are class methods. It allows you to declare a number of methods are class methods, without decalring each one on self.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337