DEV Community

Chaitali Khangar
Chaitali Khangar

Posted on • Edited on

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!!

Top comments (0)