From: badboy Date: 2009-03-09T04:37:07+09:00 Subject: Re: Setting the contents of a file to a variable? Brian Candler schrieb: > Stefan Codrescu wrote: >> ok, thanks ill try that but i also found >> file = File.open("guess.txt") >> $guess = file.gets >> which works for what im using it for. > > BTW, you forgot to close the file. Although that doesn't matter in a > short-lived script, there is a way of avoiding this problem: > > File.open("guess.txt") do |file| > $guess = file.gets > end > > This opens the file, runs the block, and then closes the file (even if > the block aborted with an exception rather than completing successfully) > > BTW, local variables which are first seen within a block are private to > that block, so if you want do use a local variable do this: > > guess = nil > File.open("guess.txt") do |file| > guess = file.gets > end > ... now 'guess' contains the result of reading the 1st line of file if you just need the content, use File.read, if you need the lines in an Array use File.readlines