Ruby的单例方法的疑惑

class B
  class<<self
    def hello
      puts "old"
    end
  end
end

class<<B
  unless self.respond_to? :hello
    def hello
      puts "new"
    end
  end
end
B.hello

执行结果为new
class B
  class<<self
    def hello
      puts "old"
    end
  end
end

class<<B
  unless B.respond_to? :hello
    def hello
      puts "new"
    end
  end
end
B.hello

执行结果为old

这几段代码的作用都是打开类B的单例类,判断是否定义了hello方法,如果未定义,则定义这个方法,但是第一段和第二段代码的执行结果大相径庭。再看两段代码
class B
  def self.hello
    puts "old"
  end
end

class<<B
  unless self.respond_to? :hello
    def hello
      puts "new"
    end
  end
end
B.hello

执行结果为new
class B
  def self.hello
    puts "old"
  end
end

class<<B
  unless B.respond_to? :hello
    def hello
      puts "new"
    end
  end
end
B.hello

输出为old
一样的结果 百思不得其解

你可能感兴趣的:(Ruby)