Last Updated: February 25, 2016
·
6.511K
· vrinek

Rename a method in Ruby

Recently I had a problem with a module that overrode the stub method with something that was not compatible with RSpec's stub. I still needed the original method in some places so I could not just remove it.

Assuming the following code:

class Animal
  def speak
    puts "..."
  end
end

class Cat < Animal
  def speak
    puts "Mew..."
  end
end

cat = Cat.new
cat.speak # Says "Mew..."

And assuming we want now to be able to access the original speak method from a Cat:

class Cat
  alias_method :mew, :speak
  remove_method :speak # removes Cat#speak, not Animal#speak
end

cat.speak # Says "..."
cat.mew # Says "Mew..."