Kernel#puts

普段使っているputsはどのクラスのメソッドなのだろう。riを使って探してみる。

C:\WORK> ri puts
More than one method matched your request. You can refine
your search by asking for information on one of:

     IO#puts, Kernel#puts, StringIO#puts, Zlib::GzipWriter#puts

いくつかある。おそらくKernel#putsなのでしょう。ではそれを確かめてみましょう。

puts "Hello, 1."

module Kernel
  def puts(x)
    raise "Kernel!"
  end
end

puts "Hello, 2."

途中でKernel#putsを再定義してしまいます。すると、Hello, 2.は表示されず、例外が発生するはず。

Hello, 1.
a.rb:5:in `puts': Kernel! (RuntimeError)
        from a.rb:9

追記:novさんからコメントでmethodメソッドを教えていただきました。感謝。なるほど、正しい解決法ですね。

p method("puts")        #=> #<Method: Object(Kernel)#puts>
p method(:puts)         #=> #<Method: Object(Kernel)#puts>

なるほど。ところでこのmethod自体もmethodで調べられる。

p method(:method)       #=> #<Method: Object(Kernel)#method>

素晴らしい。