Remove/undef a class method

后端 未结 6 1348
滥情空心
滥情空心 2020-12-13 03:59

You can dynamically define a class method for a class like so:

class Foo
end

bar = %q{def bar() \"bar!\" end}
Foo.instance_eval(bar)

But h

6条回答
  •  有刺的猬
    2020-12-13 04:26

    You can remove a method in two easy ways. The drastic

    Module#undef_method( ) 
    

    removes all methods, including the inherited ones. The kinder

    Module#remove_method( ) 
    

    removes the method from the receiver, but it leaves inherited methods alone.

    See below 2 simple example -

    Example 1 using undef_method

    class A 
        def x
            puts "x from A class"
        end
    end
    
    class B < A
        def x
            puts "x from B Class"
        end
        undef_method :x
    end
    
    obj = B.new
    obj.x
    

    result - main.rb:15:in ': undefined methodx' for # (NoMethodError)

    Example 2 using remove_method

    class A 
        def x
            puts "x from A class"
        end
    end
    
    class B < A
        def x
            puts "x from B Class"
        end
        remove_method :x
    end
    
    obj = B.new
    obj.x
    

    Result - $ruby main.rb

    x from A class

提交回复
热议问题