1.2 Track Them Losses

Knowing when methods are removed

Both method_added and singleton_method_added have equivalent methods to track when methods are removed using Module#remove_method.

They're called - you guessed it - method_removed and singleton_method_removed respectively.

As always, the best way to learn is through exercises, so lets do a couple of those.

class Dojo
class Dojo
  @@methods_removed = []
  
  def self.methods_removed
    @@methods_removed
  end
 
  def tai_kyo_kyu
  end
  
  def pinan_shodan
  end
end
 
 

Hint

This is identical to the exercise for method_added - hook into the lifecycle with method_removed, then store the name of the method being removed in @@methods_removed

Output Window

Great! Now for singleton_method_removed.

class Dojo
class Dojo
  @@singleton_methods_removed = []
  
  def self.singleton_methods_removed
    @@singleton_methods_removed
  end
  
  def self.tai_kyo_kyu
  end
  
  def self.pinan_shodan
  end
end
 
 

Hint

This is identical to the exercise for singleton_method_added - hook into the lifecycle with method_removed, then store the name of the method being removed in @@singleton_methods_removed

Output Window

As with method_added and singleton_method_added, method_removed is defined in Module and singleton_method_removed in BasicObject.

Undefined Methods

Ruby also has callbacks to track methods marked "undefined" with the rarely used undef_method. We'll cover it for completeness, but don't expect to see or use this very often.

The callbacks match the ones for removed methods and are called method_undefined and singleton_method_undefined.

class Dojo
class Dojo
  @@methods_undefined = []
  
  def self.methods_undefined
    @@methods_undefined
  end
 
  def tai_kyo_kyu
  end
  
  def pinan_shodan
  end
end
 
 

Output Window

class Dojo
class Dojo
  @@singleton_methods_undefined = []
  
  def self.singleton_methods_undefined
    @@singleton_methods_undefined
  end
  
  def self.tai_kyo_kyu
  end
  
  def self.pinan_shodan
  end
end
 
 

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2025 by Sidu Ponnappa and Jasim A Basheer