Ответ 1
#!/usr/bin/ruby -w
# Created by Michael Williams 12/19/2005
# Licensed under Create Commons Attribution License
Пример 1 - Чтение файла и закрытие:
counter = 1
file = File.new("readfile.rb", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
file.close
Пример 2: передать файл в блок:
File.open("readfile.rb", "r") do |infile|
while (line = infile.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
end
Пример 3 - Чтение файла с обработкой исключений:
counter = 1
begin
file = File.new("readfile.rb", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
file.close
rescue => err
puts "Exception: #{err}"
err
end