Question about "puts" "Kernel.puts" "Kernel::puts"
-
where are the differences bewteen puts , Kernel.puts ,Kernel::puts?
-
Thank you.
regard. -
Nothing - just one of Ruby's multiple ways of doing things.
AllKernel
methods are available available in the global scope - that is - they are available everywhere.puts == Kernel.puts == Kernel::puts
To be more specific, All objects inherit
Kernel
- because all objects inheritObject
.` Object.ancestors
=> [Object, Kernel]`
The
.
vs::
is just a syntax difference that has no affect on the behaviour.In practise people use
.
for method calls, and::
for constants.MyModule::MyClass.mymethod
MyModule::MyClass::MyConstant
-
Functionally, there is no difference.
BUT.. technically,
Kernel::puts()
, is a COPY of the instance edition ofputs()
that got mixed intoObject
, and will get inherited by ALL other classes and modules.The Ruby Core Team wrote the
Kernel
module as both a Mixin and a Library module. They used themodule_function()
method, so that all the library instance methods (that get mixin in usinginclude
,) had module method copies made. These copies can only be called by qualifying them with theKernel
module name.[ruby:1c8jtequ]Kernel.module_eval "class<<self; method(:puts).inspect; end;"
>> #<Method: Class(Kernel)#puts>
Kernel.module_eval "method(:puts).inspect;" %(#000000)[>> #<Method: Kernel.puts>]
Advertisement