Is it possible to remove a method alias in Ruby?

Suppose I have a section of Ruby code where I would like to use a method (I don’t know why, let's assume that I have a good reason).

class String
    alias_method :contains?, :include?
end

Is it possible to delete this alias after this section?

+5
source share
2 answers

remove_methodshould work in most cases. But if your alias_methodoverwrites an existing method, you may need to save the original through a separate call alias_method.

# assuming :contains? is already a method 
alias_method :original_contains?, :contains?
alias_method :contains?, :include?

Then, to restore the original state:

alias_method :contains?, :original_contains?
remove_method :original_contains?  # optional

, , , . libs , , libs, . ruby ​​2.0: http://yehudakatz.com/2010/11/30/ruby-2-0-refinements-in-practice/

, , . , -. , String ( ), String.

+5
def hello
   puts "Hello World"
end
alias :hi :hello

hi #=> "Hello World"
undef hi
hi #=> NameError
hello #=> "Hello World"

EDIT: , , main. , - Hello.class_eval("undef hi")

, , remove_method :hi, , .

class Nums < Array
   def include?
      puts "Just Kidding"
   end
end

n = Nums.new
n << 4 #=> [4]
n.include? #=> "Just kidding"
Nums.class_eval("remove_method :include?")
n.include? 4 #=> true
Number.class_eval("undef include?")
n.include? 4 #=> NoMethodError

remove_method .

+3

All Articles