O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.13. Undefining a Method

Problem

You want to remove an already defined method from a class or module.

Solution

From within a class or module, you can use Module#remove_method to remove a method's implementation, forcing Ruby to delegate to the superclass or a module included by a class.

In the code below, I subclass Array and override the << and [] methods to add some randomness. Then I decide that overriding [] wasn't such a good idea, so I undefine that method and get the inherited Array behavior back. The override of << stays in place.

	class RandomizingArray < Array
	  def <<(e)
	    insert(rand(size), e)
	  end

	  def [](i)
	    super(rand(size))
	  end
	end

	a = RandomizingArray.new
	a << 1 << 2 << 3 << 4 << 5 << 6  # => [6, 3, 4, 5, 2, 1]

	# That was fun; now let's get some of those entries back.
	a[0]                                                                 # => 1
	a[0]                                                                 # => 2
	a[0]                                                                 # => 5
	#No, seriously, a[0].
	a[0]                                                                 # => 4
	#It's a madhouse! A madhouse!
	a[0]                                                                 # => 3
	#That does it!

	class RandomizingArray
	  remove_method('[]')
	end

	a[0]                                                                 # => 6
	a[0]                                                                 # => 6
	a[0]                                                                 # => 6

	# But the overridden << operator still works randomly:
	a << 7                                                         # => [6, 3, 4, 7, 5, 2, 1]

Discussion

Usually you'll override a method by redefining it to implement your own desired behavior. However, sometimes a class will override an inherited method to do something you don't like, and you just want the "old" implementation back.

You can only use remove_method to remove a method from a class or module that explicitly defines it. You'll get an error if you try to remove a method from a class that merely ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required