Saturday, 28 September 2013

Methods don't know about outside variables?

Methods don't know about outside variables?

Say I'm writing a division algorithm script:
def current_trace
puts "Counter: #{counter}; r: #{r}; q: #{q}"
end
r = a
q = 0
counter = 0
while r >= d
current_trace
r = r - d
q = q + 1
counter += 1
end
current_trace
I expected that calling current_trace would output the value of counter, r
and q. But instead I get:
in current_trace': undefined local variable or methodcounter' for
main:Object (NameError)
What's the problem here?
How should I write a method that will output the values of some variables
named counter, r, and q, at any given point (preferably without passing
arguments to the method)?

No comments:

Post a Comment