From: Matthew Smillie Date: 2006-07-21T04:31:57+09:00 Subject: Re: recursion in scripts -- global variables required? On Jul 20, 2006, at 20:03, Eric Armstrong wrote: > Is it me, or is it pretty much impossible > to write a recursive script in ruby unless > you use global variables? > > I have a simple countdown timer. I > set up the number of seconds to sleep, > sleep for a while, and then beep. > > A single run is easily done in a script > (code below). The problems start when > I define a run method and recurse. > > Unless I use global variables, there > doesn't seem to be any way for the > variables to get the data. > > Is that about it? Well, in this case, if you're using global variables, there's not much of a point to making the method recursive (which stores all of its local variables on the stack). The typical way to do recursive method is to pass the relevant information as parameters, e.g., def countdown(seconds) sleep(1) puts "tick" sleep(1) puts "tock" countdown(seconds - 2) end I'll also mention that a deep recursion like this is a horribly inefficient way to do a countdown timer. matthew smillie > > > Initial Script > -------------- > #!/usr/bin/env ruby > > # Beeps and character I/O > require 'curses' > include Curses > > @seconds = 10 > @minutes = 0 > @hours = 0 > > #def run > timeremaining = (3600 * @hours) > + (60 * @minutes) > + @seconds > puts "sleeping for " + time_remaining.to_s > timeremaining.downto(0) do |i| > sleep(1) > print i.to_s + ".." > end > puts > beep; beep; beep > sleep 1 > beep; beep; beep > sleep 1 > beep; beep; beep > > # run > #end > > #run > > > >