Referring to variables in the scope outside the def


(k) #1

When defining a singleton method, I want to refer to variables in the scope
outside the def. Is it possible to do something like the following?

class C
def initialize
@child = Object.new
s = self
def @child.parent
s # Wrong. But how do I refer to the instance of C?
end
end
attr_reader :child
end

c = C.new
c == c.child.parent # Should be true.

Any hints? I think I’m missing a vital piece of magic here. Or maybe I’m
expecting too much Lisp-ness.

k


(Kent Dahl) #2

k wrote:

When defining a singleton method, I want to refer to variables in the scope
outside the def. Is it possible to do something like the following?

class C
def initialize
@child = Object.new
s = self
def @child.parent
s # Wrong. But how do I refer to the instance of C?
end
end
attr_reader :child
end

c = C.new
c == c.child.parent # Should be true.

Any hints? I think I’m missing a vital piece of magic here. Or maybe I’m
expecting too much Lisp-ness.

Probably the latter. A method doesn’t have access to the surrounding
scope as such. I suggest feeding it into an attribute in the child
object. Quick stab:

class C def initialize @child = Object.new s = self # feed the variable into it @child.instance_eval { @parent_C = s } # define the method for retrieving it def @child.parent @parent_C end end attr_reader :child end

c = C.new
puts c == c.child.parent # Is now true

HTH

···


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 4. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)


(ts) #3

    def @child.parent
      s # Wrong. But how do I refer to the instance of C?
    end

Use #send if you need to access only local variables, or C instance
variables

Guy Decoux