ルビーの一例方法の疑惑

1413 ワード


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メソッドが定義されているか否かを判断し,定義されていない場合はこのメソッドを定義するが,第1セグメントと第2セグメントコードの実行結果は大きく異なる.2つのコードを見てください

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
同じ結果ではどうしても理解できない