ruby Kernel: method behaves as instance method

class C
  def aaa
     print "aaa"
  end
end

C.new.aaa
# => "aaa"

now works method print from module Kernel

Kernel.methods.grep /^print/
# => [:printf, :print]

this means, that this method defines as class method.

Kernel doesn't have instance method print

Kernel.instance_methods.grep /^print/
# => []

So the first question is: How could it be, that class method calls from the object receiver? (C.new)


Also I tried do the same trick with own Module:

module M
  def self.print
    "111"
  end
end

class C
include M
  def aaa
     print 
  end
end

C.new.aaa
# => nil

You see, again it is Kernel module

but hierarchy tree is:

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

M.methods.grep /^print/
# => [:print]

method defined as in Kernel. I can override only as instance method

module M
  def print
    "111"
  end
end


M.instance_methods.grep /^print/
# => [:print]

so how Kernel do this? how Kernel puts class method as instance method?

Answers


1.9.3-p327 :002 > Kernel.private_instance_methods.grep /^print/
=> [:printf, :print]

instance_methods only gives you a list of public instance methods. Since Kernel is included by Object, its private instance methods are always available, so there's no need to make them public.


Need Your Help

Comparing two Array in C#

c# arrays compare

I am new to C# and just comparing two arrays... both arrays should be equal, as their values are same, but result is always false... not sure why.

How would you manage X509 authentication on a Django app behind a Nginx proxy?

django nginx x509certificate x509

I would like to use a X509 client authentication for a secure API access.