新手问题 一个关于 undef_method 的新手问题,希望有人指点

bluetea · January 20, 2015 · Last by fahchen replied at January 21, 2015 · 1575 hits
class A < Array
  def self.hide(name)
    if instance_methods.include?(name.to_s) and name !~ /^__|instance_eval/
      undef_method name
    end
  end
  instance_methods.each {|m| p "deleted #{m}"; hide(m)}
end

a = A.new
a = [1,2,3]
a.each {|i| p i}

执行之后,那些方法都没有被删除 代码是根据《元编程》第 64 页 改的,望有高手指点!--非常感谢!

基础不牢,还不到能看元编程的时候,先把基础打牢。

a = A.new
a = [1,2,3]

基础达到的话就知道这两行发生了什么。

除了楼上说的问题,还有一个问题

instance_methods.include?(name.to_s)

这里的 instance_methods 返回的是一个元素都为 symbol 的数组,自然 name.to_s 一个都不被包括在里面了

You need to Sign in before reply, if you don't have an account, please Sign up first.