新手问题 Ruby 的类方法怎么进行动态删除

winse · April 19, 2017 · Last by winse replied at April 19, 2017 · 1617 hits

我有一个 A 类

class A
  def a
    puts 'this is method a'
  end

  def self.b
    puts 'this is method b'
  end
end

我可以删除方法 a

a = A.send :remove_method, :a
A.new.methods(false)     # => []

然而我没有找到删除类方法的方式

class << A
 undef :b
end

类方法就是类对象的单例类的实例方法,所以同理 A.singleton_class.send :remove_method, :b

Reply to shinkxw

哦哦,还有 我以为:remove_method 返回的是删除掉的方法,结果不是,我应该用哪个方法获得被删除的方法?

Reply to winse

删除前使用 a = A.new.method(:a) 获取

Reply to shinkxw

感谢😋

winse closed this topic. 19 Apr 14:07
You need to Sign in before reply, if you don't have an account, please Sign up first.