1

I've got a Ruby class and in the initialization of the class, the user provides a filepath and filename, and the class opens the file.

def Files
  def initialize filename
     @file = File.open(filename, "r").read.downcase.gsub(/[^a-z\s]/,"").split 
  end

  def get_file
      return @file
  end

end

However, the problem is that the user can provide a file that doesn't exist, and if that is the case, I need to rescue so we don't show an ugly response to the user.

What I'm thinking of is something like this

def Files
   def initialize filename
      @file = File.open(filename, "r").read.downcase.gsub(/[^a-z\s]/,"").split || nil
   end
end

Then in the script that calls the new file I can do

def start
  puts "Enter the source for a file"
  filename = gets
  file = Files.new filename

  if file.get_file.nil?
    start
  else
    #go do a bunch of stuff with the file
  end
end

start

The reason I'm thinking this is the best way to go is because if the file that is passed in is large, I'm guessing it is probably best to not pass a huge string of text into the class as a variable. But that might not be right.

Anyway, I'm really trying to figure out the best way to handle the case where an invalid file is entered.

4

1 回答 1

2
def Files
  def initialize filename
    return unless File.exist?(filename)
    @file = File.read(filename).downcase.gsub(/[^a-z\s]/,"").split
  end
end
于 2013-10-15T08:49:59.133 回答