What is the clearest way to open a file and do "rescue" when it cannot be opened in Ruby

user3477465 picture user3477465 · Apr 6, 2014 · Viewed 8.7k times · Source

I am now dealing with this issue by using the following code

begin
  File.open(filename, 'r')
rescue
  print "failed to open #{filename}\n"
  exit
end

Is there any way to do it more easily like Perl 'open (IN, $filename) || die "failed to open $filename\n"' Thanks.

Answer

steenslag picture steenslag · Apr 6, 2014
File.open("doesnotexist.txt", 'r')

Is enough. If the file does not exist, this will raise an Exception. This is not caught, so the program exits.

# =>test6.rb:1:in `initialize': No such file or directory @ rb_sysopen - doesnotexist.txt (Errno::ENOENT)