In my opinion, class << self was one of the most annoying bits of syntax in Ruby. People unfamiliar with the language have no idea what this means, except for purchase-cult agreements, and even those who are familiar with the language have only a vague understanding of what makes it different from instance_method , because these two seem surprisingly similar.
Here is an example of two different ways to define a class method:
class Example class << self def class_def :class_def end end instance_eval do def instance_def :instance_def end end end
You can verify that they work by calling methods:
puts Example.class_def.inspect # => :class_def puts Example.instance_def.inspect # => :instance_def
The difference is that you dynamically create methods using define_method , since the binding is really incorrect in the instance_eval version:
class Example class << self define_method(:class_def) do :class_def end end instance_eval do define_method(:instance_def) do :instance_def end end end
This leads to the definition of the instance_def method, but not tied to the class itself:
puts Example.class_def.inspect # => :class_def puts Example.instance_def.inspect # => NoMethodError: undefined method 'instance_def' for Example:Class
The only reliable way to create dynamic methods is class << self . The instance_def method is apparently created and discarded because it does not appear in the Example.method methods even inside this block.
source share