views:

517

answers:

3

Hi All,

Quick question regarding the use of "SELF" inside a module or library. Basically what is the scope/context of "SELF" as it pertains to a module or library and how is it to be properly used? For an example of what I'm talking about, check out the "AuthenticatedSystem" module installed with "restful_authentication".

Best

NOTE: I'm aware that 'self' equates to 'this' in other languages and how 'self' operates on a class/object, however in the context of a module/library there is nothing to 'self'. So then what is the context of self inside something like a module where there is no class?

A: 

'self' is the equivalent of 'this' in ruby.

jonnii
A: 

For a short summary... http://paulbarry.com/articles/2008/04/17/the-rules-of-ruby-self

self is also used to add class methods (or static methods for C#/Java people). The following snippet is adding a method called do_something to the current class object (static)...

class MyClass
    def self.do_something   # class method
       # something
    end
    def do_something_else   # instance method
    end
end
Gishu
+2  A: 

In a module:

When you see self in an instance method, it refers to the instance of the class in which the module is included.

When you see self outside of an instance method, it refers to the module.

module Foo
  def a
    puts "a: I am a #{self.class.name}"
  end

  def Foo.b
    puts "b: I am a #{self.class.name}"
  end

  def self.c
    puts "c: I am a #{self.class.name}"
  end
end

class Bar
  include Foo

  def try_it
    a
    Foo.b # Bar.b undefined
    Foo.c # Bar.c undefined
  end
end

Bar.new.try_it
#>> a: I am a Bar
#>> b: I am a Module
#>> c: I am a Module
Sarah Mei
Precisely. Everything is an object in Ruby. There is no place code can be executed where there isn't a self.
Chuck
Understood, so then what is the scope/purpose of calling self in a module?
humble_coder
Hi All,Still looking for an explicit answer. I realize what SELF *can* do. What I need to know is exactly what it *does* do in a function of a module? I would guess that some type of variable is set globally, but I'm not sure if this is the case. Can anyone confirm/enlighten?
humble_coder
I guess I don't really understand your question. What does it do? It serves as a reference to the enclosing object. In a module, outside of an instance method, it serves as a reference to the module itself. In a module but inside an instance method, it serves as a reference to the instance of the enclosing class.
Sarah Mei