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.
AllKernelmethods are available available in the global scope - that is - they are available everywhere.puts == Kernel.puts == Kernel::putsTo 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
Kernelmodule 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 theKernelmodule 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>]
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better đź’—
Register LoginAdvertisement