From: Peter Vandenabeele Date: 2011-09-29T19:07:40+09:00 Subject: Re: IO.readlines will not accept variable with file name Why? --20cf302ef912af853a04ae11ad40 Content-Type: text/plain; charset=UTF-8 On Thu, Sep 29, 2011 at 11:56 AM, Robert Klemme wrote: > On Thu, Sep 29, 2011 at 11:14 AM, Joda jenson wrote: > > I am fairly new to Ruby and I am stuck on this. Would someone have a > > suggestion. > > > > I'm trying to read a file with IO.readlines, letting a user give the > > file name. > > __________________________________________________ > > puts "what is the name of the file=>" > > filename1 = gets > > > > filearray = IO.readlines(filename) > > puts filearray [0] > > __________________________________________________ > > > > If I hard code the file name works great. > > > > filearray = IO.readlines("/home/user/file.txt") > > > > __________________________________________________ > > It seems to be something to do with the double quotes. > > I have tried to wrap the variable with double quotes. > > > > filename1 = ("\"/home/user/file.txt\"") > > > > It will print the Double quote but still will not work if I pass it to > > the IO.readlines() > > > > It gives a (Errno::ENOENT) > > > > It doesn't seem to matter how I doctor a string with quotes I can't get > > IO.readlines() to accept it. Only hard coding it works for some reason. > > Insert a line after "gets" like this: > > puts "what is the name of the file=>" > filename1 = gets > p filename1 # look at the output > > filearray = IO.readlines(filename) > puts filearray [0] > > You'll immediately see what's wrong. :-) > > I am not sure. I think it is a simple typo in that filename1 (with a digit) is asked by the get, but filename (without a digit) is used in the call to IO.readlines. IMHO, the code as shown above could never work with that typo ... HTH, Peter --20cf302ef912af853a04ae11ad40--