DEV Community

wuletaw wonte
wuletaw wonte

Posted on • Originally published at wuletawwonte.com on

The Kernel module in Ruby

When hearing the word Kernel someone from system administration world like me may think it is referring to the famous Operating System kernel Linux. That is exactly what I though when I read about it for the first time. The fact is it is just a ruby convention, not directly related to the operating system kernel. Let’s see what it means in Ruby

As the word ‘kernel’ , or Linux itself in an Operating System, refers to the central component of the operating system that provides core services and functionalities, the Kernel module in ruby can be seen as a core component that provides essential methods for Ruby Objects.

class Movie; end
print Movie.ancestors
# Output
# [Movie, Object, Kernel, BasicObject]
Enter fullscreen mode Exit fullscreen mode

As you can see in the example above the Kernel is part of the ancestor chain of the Movie class. Does that mean the Kernel is the super class of the Object class? No, the ancestor chain not only shows classes and super classes but also modules. In this case the Object class included the Kernel module and that’s why it is listed in the ancestor chain.

Methods defined in the Kernel module often provide low-level functionality, such as interacting with the operating system, handling exceptions, or perform common utility operations. print, puts, and gets are few of the common utility methods provided by the Kernel module.

Since the Kernel module is included in the Object class, all methods from the kernel module are accessible to all Ruby objects. This feature allows you to leverage Monkey Patching, where adding methods to the Kernel module automatically makes them available to all Ruby objects.

Here is an example of a Ruby library leveraging Monkey Patching the Kernel module. The awesome_print gem prints Ruby objects on the screen with indentation, color and other variations.

require "awesome_print"

my_object = {name: "Wuletaw Wonte", country: "Ethiopia"}
ap my_object

# Output
{
    name: "Wuletaw Wonte",
    country: "Ethiopia"
}
Enter fullscreen mode Exit fullscreen mode

You can call ap from anywhere because it is added to the Kernel module in the gems source code.

# gems/awesome_print-1.1.0/lib/awesome_print/core_ext/kernel.rb
module Kernel
  def ap(object, options = {})
    # method code ...
  end
end
Enter fullscreen mode Exit fullscreen mode

The post The Kernel module in Ruby appeared first on Wuletaw Wonte.

Top comments (0)