Ruby’s Kernel Module

Kernel is a module that’s mixed in to the Object class and contains several core methods like gem() and puts() that almost look like language keywords. Except in rare instances, all Ruby objects inherit from Object and have access to the methods defined in Kernel. The ancestors() method demonstrates that Kernel is mixed into Object (mixed-in modules are to the right of the class they’re mixed in to):

Object.ancestors # => [Object, Kernel, BasicObject]

All Ruby modules are instances of the Module class, similar to how all class objects in Ruby are instances of the Class class.

Kernel.class # => Module
module ABC; end
ABC.class # => Module

Several Kernel methods are private instance methods, meaning they cannot be called with an explicit receiver other than Kernel.

# raises an exception because Kernel#puts is a private instance
# method and cannot be called with an explicit receiver (A)
class A
  self.puts 'hi'
end

# works because no explicit receiver is used
class B
  puts 'hi'
end

# private methods can be called when the explicit receiver defines
# the method
Kernel.puts 'hi'

Virtually all Ruby objects inherit from Object and have access to the methods defined in the Kernel module, so Kernel’s private instance methods are accessible virtually anywhere in a Ruby program, regardless of self.

self # => main
self.class.ancestors.include? Object # => true
self.private_methods.include? :puts # => true

class A
  self # => A
  self.ancestors.include? Object # => true
  self.private_methods.include? :puts # => true

  def a_method
    self # => instance of A
    self.class.ancestors.include? Object # => true
    self.private_methods.include? :puts # => true
  end
end

puts() will continue to work as the self keyword changes because all objects are inheriting from Object.

Kernel is a vital module and defines several core methods used commonly in Ruby programming. Studying Kernel closely is a good way to learn about mixing in modules, private methods, and the value of self based on program context.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s