"HarryO" <harryo / zipworld.com.au> writes:

> 
> Here's a question, though.  If I have a global function (or any function,
> for that matter) and call it from within the context of a class, can I
> findout the class of the caller?  Eg,
> 
>   def fred(text)
> 	# How can I find out who called me here?
>   end
> 
>   class Jim
> 	fred("Hello")
>   end

'self' is available.  Remember that in Ruby, global methods aren't
global methods. They are methods in Object. You can access them not
because they're global, but because Object is the parent of all
objects in the system, and therefore you're simply invoking a method
in your superclass. As such, the method is being invoked in your
context. That means you can do slightly devilish things :)

  def fred
    p self.class
    p self.name
  end

  class Jim
    fred       #=>  Class
  end               "Jim"


and

  def fred
    p self
    @x = 99
  end

  class Dave
    attr_reader :x
    def initialize
      @x = 1
    end

    def call_fred
      fred
    end
  end

  d = Dave.new
  p d.x
  d.call_fred
  p d.x

which produces

  1
  #<Dave:0x401b3540  @x=1>
  99


See - it really is just an instance method that happens to be in
_every_ object.

I _love_ the orthogonality here.



Dave