I usually use puts and print, but I wondered who this is, so when I looked it up, it seems to be a method included in the kernel module. Since it became "Kernel module?", I checked it.
A module that defines methods that can be referenced by all classes. The Object class includes this module. The methods of the Object class are actually defined in this module. This is to accommodate method redefinition at the top level.
First, there are all superclasses called Object classes, and the methods defined here can be used for all objects. And since the Karnel module is included in this Object class, the result is that the method can be used anywhere. (By the way, a module is a function that cannot be instantiated like a class, but can define constants and methods.)
Like this.
talk.rb
#This part is the top level(Outside a class or module)
def say
puts "hello"
end
#This part is the top level
#Since the Human class inherits the Object of the parent class, the say method can be used.
class Human
def talk
say
end
end
human = Human.new()
human.talk
#=>hello
I did my own research, but I would appreciate it if you could point out any mistakes.
Object-oriented scripting language Ruby reference manual https://docs.ruby-lang.org/ja/latest/class/Kernel.html
Top level in Ruby https://www.javadrive.jp/ruby/method/index1.html
What is Ruby's top-level method after all? https://qiita.com/pink_bangbi/items/c08ec7b32fc6dd20baad
Recommended Posts