scope when reopening method

R

Rahul Kumar

Here is a dummy class with a method "meth".

class My

# str contains some value generated by My
def meth str
end

def call_meth
meth "abc"
end
end


# ------ my application starts here

arr = []

m = My.new
def m.meth(str)
# access some other object in application scope
arr << str
do_something str # call some method in my app
end

I have the method "meth" above which is of interest to user apps.
The app overrides the method and would like to access methods or
variables
in my application scope.

Is there anyway this is possible (other than using global variables) ?
To me it appears that meth() can only access what is in that objects
scope plus globals. thx.
 
J

Jesús Gabriel y Galán

Here is a dummy class with a method "meth".

=A0 class My

=A0 =A0 =A0# str contains some value generated by My
=A0 =A0 =A0def meth str
=A0 =A0 =A0end

=A0 =A0 =A0def call_meth
=A0 =A0 =A0 =A0 meth "abc"
=A0 =A0 =A0end
=A0 end


=A0 # ------ my application starts here

=A0 arr =3D []

=A0 m =3D My.new
=A0 def m.meth(str)
=A0 =A0 # access some other object in application scope
=A0 =A0 arr << str
=A0 =A0 do_something str # call some method in my app
=A0 end

I have the method "meth" above which is of interest to user apps.
The app overrides the method and would like to access methods or
variables
in my application scope.

Is there anyway this is possible (other than using global variables) ?
To me it appears that meth() can only access what is in that objects
scope plus globals. thx.

If I understand correctly, you want the meth method defined for object
a to be able to access methods and instance variables defined in the
My class. Nothing special needs to be done:

irb(main):001:0> class My
irb(main):002:1> def initialize
irb(main):003:2> @value =3D 3
irb(main):004:2> end
irb(main):005:1> def do_something
irb(main):006:2> puts "my value is #{@value}"
irb(main):007:2> end
irb(main):008:1> def call_meth
irb(main):009:2> meth "abc"
irb(main):010:2> end
irb(main):011:1> def meth str
irb(main):012:2> str * 2
irb(main):013:2> end
irb(main):014:1> end
=3D> nil
irb(main):015:0> My.new.call_meth
=3D> "abcabc"
irb(main):016:0> a =3D My.new
irb(main):025:0> def a.meth str
irb(main):026:1> do_something
irb(main):027:1> str + @value.to_s
irb(main):028:1> end
=3D> nil
irb(main):029:0> a.call_meth
my value is 3
=3D> "abc3"

Maybe I misunderstood the question.

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top