[LRUG] Global methods vs. Kernel mixins

Hemant Kumar hemant at codemancers.com
Thu Jul 18 01:29:48 PDT 2013


Hello,


On 18-Jul-2013, at 1:21 PM, Rob Miller <rob at bigfish.co.uk> wrote:

> Thanks, that clears some things up — but I'm still left with the question of why you'd do that rather than just defining a global method? Seems an unnecessary hoop to jump through. 

In Ruby no matter where you are, you always have a `self` object. When you inside a instance method of a class, self is the instance of that class. When you are defining a class method, `self` is the class. 

Ruby also has a concept of "default definee". When you define a method without an explicit receiver, the method is defined as instance method in the "default definee" class. 

When you are in global scope, the self is an object called 'main'.  Object 'main' is a very special object in Ruby. It is an instance of class `Object` itself and very curiously has dual nature, which means it can behave as an object and sometimes as a class.

Banister has written some good material on nature of this "main" object:

http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

So what does this leaves us with? global methods defined in "main" object are mixed into Object class as private instance methods and hence are available everywhere but as private method (other than object main itself).

In a nutshell:

def foo; end

and 

module Kernel
  def foo; end
end

Are not same at all. :-)



Cheers
Hemant
http://twitter.com/gnufied
http://www.codemancers.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20130718/365bda2e/attachment-0003.html>


More information about the Chat mailing list