From: Austin Ziegler Date: 2002-10-22T06:33:22+09:00 Subject: Re: functional Ruby equiv to this perl snippet On Tue, 22 Oct 2002 05:54:49 +0900, Bob X wrote: > Cool..but what if serverlist.txt does not exist? The one thing I do > like about Perl is the "open file or die" test. I believe that I am > "stuck" with a rescue clause which is sometimes confusing for me (a > newbie) to use when it is located within a "def". Truth be told, you don't need to "or die". If you run the following code (a minor modification to parameterize the filename), you'll get (assuming, of course, that serverlist2.txt doesn't exist): c:/home/Projects/Ruby/test.rb:4:in `initialize': No such file or directory - "se rverlist2.txt" (Errno::ENOENT) from c:/home/Projects/Ruby/test.rb:4:in `open' from c:/home/Projects/Ruby/test.rb:4:in `load_server_list' from c:/home/Projects/Ruby/test.rb:13 def load_server_list(filename) servers = [] File.open(filename).each do |line| next unless line =~ /^\S+$/ next if line =~ /^#.*$/ servers << line.chomp.sub(/\s+#.*$/, '') end servers end servers = load_server_list('serverlist2.txt') p servers.size, servers To handle it as a caller, just replace the last two lines with something like: begin fn = 'serverlist2.txt' servers = load_server_list(fn) rescue Errno::ENOENT => ex puts "Problem reading \"#{fn}\".\n\t#{ex.message}" exit end File.open automatically raises an error. Where you might want to do something different is to have your own FileNotFoundException, like so: class FileNotFoundException < RuntimeError end def load_server_list(filename) servers = [] File.exist?(filename) or raise FileNotFoundException, filename File.open(filename).each do |line| next unless line =~ /^\S+$/ next if line =~ /^#.*$/ servers << line.chomp.sub(/\s+#.*$/, '') end servers end begin servers = load_server_list('serverlist2.txt') rescue FileNotFoundException => fnf puts "File '#{fnf.message}' does not exist." exit end If there is anywhere that I think that Ruby's class model is a bit weak, it's in the existence of and documentation of 'standard' exceptions. IMO, Errno::ENOENT is not what File.open should throw, even though that's the actual errno value received -- it should throw an appropriate readable exception (like FileNotFoundException) or something like that. -austin -- Austin Ziegler, austin@halostatue.ca on 2002.10.21 at 17.17.05