From: Sean O'Halpin Date: 2006-07-26T18:15:40+09:00 Subject: Re: get caller of method On 7/26/06, Ashley Moran wrote: > On Sunday 23 July 2006 22:55, Sean O'Halpin wrote: > > Hi, > > > > It's not clear to me what you're doing with the binding. You don't > > need it for your example and it won't work the way you seem to think. > > > > The example below shows you don't need to do anything fancy to get hold of > > self: > > > > < SNIP bit that shows me up as clueless :) > Don't take it so hard - we're all still learning :) > > > > > Please feel free to correct me if I've gotten hold of the wrong end of > > the stick (it has been known ;) > > > > Regards, > > Sean > > > Hi Sean > > Seems I misunderstood the scope of "self". I assumed that since a Food > instance was calling a method in another object (the application instance of > Object) that self would be the global "main" object. IE: > > irb(main):003:0> class Foo > irb(main):004:1> def test > irb(main):005:2> global_test > irb(main):006:2> end > irb(main):007:1> end > => nil > irb(main):008:0> def global_test > irb(main):009:1> puts self.class > irb(main):010:1> puts self.inspect > irb(main):011:1> end > => nil > irb(main):012:0> Foo.new.test > > I expected: > Object > main > > But you actually get: > Foo > # > > > I have to say, I don't understand this behaviour. Maybe I am missing > something. I assume it is to do with class nesting? > > Ashley > self is dynamically scoped to always return the current receiver. It is not lexically scoped, i.e. it does not depend on ~where~ the definition is but on how it is called. Look at this example: @name = "I'm main" def name @name end def m1 p [self, name] @name = name.reverse end m1 # called in scope of self == main class Foo attr_accessor :name def initialize(name) @name = name end def name @name end def m2 m1 # called in scope of self == instance of Foo end end f = Foo.new("I'm foo") f.m2 f.m2 __END__ [#, "I'm main"] [#, "I'm foo"] [#, "oof m'I"] HTH Regards, Sean