From: David Alan Black Date: 2002-06-22T17:29:56+09:00 Subject: Re: What do you think of this idiom? Hi -- On Sat, 22 Jun 2002, Hal E. Fulton wrote: > I was writing a little script which prompted > the user for a directory. I wanted to repeat > until a valid directory was entered. > > At first I was going to write an actual loop. > Then I thought of this little technique. What > do you think? How would you do it? > > Cheers, > Hal Fulton > > > begin > print "Dir = " > mydir = gets.chomp > dir = Root + mydir > raise "No such directory" if not File.stat(dir).directory? > rescue => err > puts err > retry > end I think it isn't doing what you think :-) $ ruby getdir.rb # with "Root = './'" added Dir = non-existent No such file or directory - "./non-existent" Note that it's not using your error message, because the "if not" branch never happens: the stat on a bad directory name raises an exception of its own. You could use test(?d,dir) to get a true/false test. Anyway, I like the way "retry" fits in here, and this seems like a good way to avoid the annoying pattern of repeating a test, which I always seem to fall into: until some_test(str) print "Input: " str = gets.chomp puts "Invalid" unless some_test(str) end Ultimately, though, it would be nice to wrap all this stuff up in a method. I was playing around with that a little, using yours as a starting point. Nothing profound here, just curious how the wrapping might go. def getstr(prompt,error="Invalid input") str = "" # not strictly needed, but clearer begin print prompt str = gets.chomp raise error unless yield(str) rescue => err puts err retry end str end s = getstr("Dir = ", "No such directory") {|dir| test(?d,dir)} David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav