From: dblack@... Date: 2002-10-22T11:34:02+09:00 Subject: Re: What I did (was Re: functional Ruby equiv to this perl snippet) Hi -- On Tue, 22 Oct 2002, Bob X wrote: > Here is what I did...with your help and looking through different ways to > handle stuff. > > # get the servers out of the file > def load_server_list > servers = [] > filename = 'serverlist.txt' > if FileTest.exist?(filename) > File.open(filename).each do |line| Just to point out that you're introducing a wee race condition, because it's possible for the file to be deleted (by another process) between the exist? test and the open. This may not be a practical consideration in this case, but it's probably not a good construct to use in general. > next unless line =~ /^\S+$/ That's going to reject every line that has whitespace in it (not counting the final \n); for example, both of these lines will be rejected: some_server_name # this line will be rejected another_server_name > next if line =~ /^#.*$/ The .*$ part is superfluous -- it will always match if ^# matches :-) Here's a version that (I think) rejects comment lines and blank lines, strips trailing comments, and returns the first non-space-containing string it finds on a line. (You can wrap it in filetests if you wish :-) def load_server_list filename = 'serverlist.txt' File.open(filename).map do |line| Regexp.last_match[1] if /^\s*([^#\s]+)/.match(line) end .compact end On the exception vs. filetest matter: remember that to handle an exception you don't have to write it into the method. For example, when you call the method you can do: begin load_server_list rescue => e puts "Something went wrong: #{e}" end (I mention this because I think you said something before about not wanting to write an exception handler directly in the method definition.) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav