DEV Community

Chaitali Khangar
Chaitali Khangar

Posted on • Edited on

1

The Curious Case of puts: A Ruby Detective Story

Ever wonder where the puts method comes from in Ruby?

Let's check out that together.

puts.class # => NilClass
Enter fullscreen mode Exit fullscreen mode

It returns NilClass. But why?

It's because calling puts without arguments returns nil, signifying the absence of a specific value.

NilClass represents this very concept – the lack of a defined value.

Now, to unravel the true origin of puts, we will execute this code:

puts_method = method(:puts)
puts puts_method.owner
Enter fullscreen mode Exit fullscreen mode

This code reveals that puts originates from the Kernel.

Let's check out whether Kernel is a class or a Module.

Kernel.is_a? Class #=> false
Kernel.is_a? Module #=> true
Enter fullscreen mode Exit fullscreen mode

This clarifies that Kernel is a module.

But, how do puts magically work without a receiver?

In Ruby, the "Object" class includes the Kernel module.

This makes Kernel an essential part of every object's ancestry.

As Ruby code runs within an object, you can call Kernel's instance methods from anywhere in your code.

So, next time you use 'puts' in your Ruby code, remember its origins in the Kernel module and how it seamlessly integrates into every object's ancestry, making it accessible from anywhere in your code.

Image descriptionTill we meet, Happy Coding!!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay