Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Array method confusion

we can call the Array method in the top level like this

Array(something)

that makes sense to me, it's a method call without explicit receiver, and self, which is main in this case, is inserted at the front of the method call. But isn't it that this is equivalent to :

Kernel.Array(something)

this doesn't make sense to me. Since in the first case, the object main is of class Object, which got Kernel module mixed in, thus have the Array method. But in the second case, we are calling the Array method on the Kernel module object itself, rather than main object, didn't they are NOT the same thing?

sorry for my bad english.

like image 808
freenight Avatar asked Dec 06 '09 11:12

freenight


1 Answers

Kernel.Array is what is known as a module function. Other examples of module functions include Math.sin, and Math.hypot and so on.

A module function is a method that is both a class method on the module and also a private instance method. When you invoke Array() at the top-level you are invoking it as a private instance method of the main object. When you invoke it through Kernel.Array() you are invoking it as a class method on Kernel. They are the same method.

To learn more, read up on the module_function method in rubydocs: http://www.ruby-doc.org/core/classes/Module.html#M001642

like image 55
horseyguy Avatar answered Oct 16 '22 11:10

horseyguy