As noted above, both styles seem to be equivalent, however using class << self
allows one to mark class methods as private
or protected
. For example:
class UsingDefSelf
def self.a; 'public class method'; end
private
def self.b; 'public class method!'; end
end
class UsingSingletonClass
class << self
def a; 'public class method'; end
private
def b; 'private class method'; end
end
end
private
only affects instance methods. Using the singleton class, we are defining instance methods of that class, which turn into class methods of the containing class!
We can also mark class methods as private
with def self
:
class UsingDefSelf
def self.a; 'private class method'; end
def self.b; 'private class method!'; end
private_class_method :a, :b
# In Ruby 2.1 there is an alternative syntax
private_class_method def self.c; 'private class method!'; end
end
But we cannot mark them as protected
, there is no protected_class_method
. (However, since class is the only instance of its singletonclass, private class method and protected class methods are almost the same except their calling syntax is different.)
Also it is less easier than using class << self
to mark private
class methods, since you have to list all method names in private_class_method
or prefix private_class_method
to every private class method definition.