0

It sounds stupid but it has given me 3 hr of head banging...!! I have created a class method in which I am extracting a file base name (placed in the Root folder). The issue is IO.readlines method is not accepting the file with a base name returned from the fetching. It returns error:

./lib/fileCheck.rb:36:in `readlines': No such file or directory -  (Errno::ENOENT)

But it works as soon as I manually enter the file base name in readlines. Here is the class method:

class FileCheck
  def self.read_file
    file = File.basename(Dir[File.join(File.expand_path('../.'), "*.txt")].to_s)
    file = IO.readlines(file)
    return file
  end
end

No result, but as soon as I place the file name manually, it works perfectly.

  def self.read_file
  #file = File.basename(Dir[File.join(File.expand_path('../.'), "*.txt")].to_s)
  file = IO.readlines('sample.txt')
  return file
 end

I check with irb and the statement

File.basename(Dir[File.join(File.expand_path('../.'), "*.txt")].to_s) 

is returning a file base name of class String.

Any suggestions?????

4

1 回答 1

1

expand_path使用or没关系join。您的代码中仍然存在市长问题:

File.basename(Dir[File.join(File.expand_path('../.'), "*.txt")].to_s) 

Dir[]也称为返回Dir.glob数组!确保选择其中一个元素而不是调用to_s. 当有多个文件时,您会遇到问题。

于 2013-10-22T14:31:22.473 回答