Ruby - Using ensure clause to do file closing

Description

Using ensure clause to do file closing

Demo

f = File.new( "main.rb" )
begin#  w w w. j  a  v  a  2s. c  o  m
    for i in (1..6) do
        puts("line number: #{f.lineno}")
        line = f.gets.chomp
        num = line.to_i
        puts( "Line '#{line}' is converted to #{num}" )
        puts( 100 / num )
    end
rescue Exception => e
    puts( e.class )
    puts( e )
ensure
    f.close
    puts( "File closed" )
end

Result

Related Topic