How to rescue an input in class initialization
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-zs]/,"").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-zs]/,"").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.
def Files
def initialize filename
return unless File.exist?(filename)
@file = File.read(filename).downcase.gsub(/[^a-zs]/,"").split
end
end
链接地址: http://www.djcxy.com/p/25274.html
上一篇: 如何使用PubkeyAuthentication = no选项下载文件
下一篇: 如何在类初始化中拯救输入
