1

Ruby programmers typically use class << self inside a class body to open up the class object's eigenclass, like so:

class Foo
  class << self
    # ...
  end
end

However, I seldom see this equivalent form (assume that Foo is already defined to be a class):

class << Foo
  # ...
end

Is there a reason for preferring the first style to the second?

Community
  • 1
  • 1
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 1
    Stylistically, it makes the operation easier to see with a consistent idiom. – user2864740 Jul 16 '14 at 19:06
  • I expect the same answer would apply if you asked why class methods are generally defined `def self.a ... end`, rather than `def A.a ... end`. In both cases, the use of `self` reduces by one the number of lines in your code that require attention if you rename the class. I can't think of any other benefit. – Cary Swoveland Jul 17 '14 at 00:11

1 Answers1

3

When using class << Foo, or when defining explicitly def Foo.some_method(args) you are repeating the name of the class.

Using class << self is DRYer, and makes refactoring easier (changing the class name is done in one place, and does not have to be repeated in the code), as well as copy+paste to other classes/projects.

class Foo1
  # ..
end

class << Foo # <- :(
  #..
end
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
  • 1
    There's no repetition in the OP's examples. Both mention `Foo` exactly once. – Jörg W Mittag Jul 16 '14 at 20:05
  • 2
    @JörgWMittag - from the OP `(assume that Foo is already defined to be a class)` - if it was not mentioned before you'd get `uninitialized constant Foo` – Uri Agassi Jul 16 '14 at 20:16
  • @JörgWMittag The OP says that the class is defined elsewhere for the second example. So if that (elsewhere-defined) class were ever renamed, you'd have to change the name in the second example. Instead the first example, provided it's defined in the file where the class name is specified, wouldn't need to change. – Benissimo Jul 16 '14 at 20:16
  • 3
    Anyone who prefers using `def self.xyz` method over either solutions? – konsolebox Jul 16 '14 at 20:21
  • 1
    @UriAgassi What about the case where you're opening a class's eigenclass in a different file from where the class was defined? (e.g., monkey-patching a built-in class.) You don't get to escape naming the class in that case, so is there a benefit to still using `class Object; class << self` vs `class << Object`? – C. K. Young Jul 16 '14 at 23:07
  • 1
    @ChrisJester-Young - I think in this case the most notable advantage for `class << self` is conformity - there is no point in using a less ubiquitous syntax because it saves a few characters, only to have it harder to read since it is less well-known. – Uri Agassi Jul 17 '14 at 04:41