Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kernel.pp raises NoMethodError in Ruby

Tags:

ruby

I am using Ruby 2.6.3

Ruby ri documents pp as:

prints arguments in pretty form.

Anyways, in a file, when I write and run the following code:

#!/usr/bin/ruby -w

Kernel.pp 'hi'
pp 'hi'

I get NoMethodError.

But how does the following code work?

#!/usr/bin/ruby -w

pp 'hi'
Kernel.pp 'hi'

Output:

"hi"
"hi"

Here's a screenshot

like image 968
S.Goswami Avatar asked Mar 22 '26 21:03

S.Goswami


1 Answers

The actual pp method is implemented in a module shipped with Ruby which is also called pp. With older Rubies, in order to use the method, you had to always run

require 'pp'
pp "foo"

Newer Rubies ship with a convenience method in Kernel#pp which automatically requires the pp module and runs the method. After the first invocation of this method (and thus with the require of the module), the former method is replaced with the actually intended pp method.

Thus, if you first run the instance method pp (which is available as a private method on all Objects in Ruby which include the Kernel module, i.e. about all Objects), the pp module is loaded and the other methods (including the Kernel.pp class method becomes available.

like image 147
Holger Just Avatar answered Mar 25 '26 00:03

Holger Just