1

不确定这里发生了什么,或者在这种情况下可能是整数。这是代码:

def build_array_from_file(filename)
    contents = []
    File.read(File.expand_path('lib/project_euler/' + filename), 'r') do |file|
      while line = file.get
        contents << line
      end
    end
    contents
  end

文件名是一个字符串,我已经检查以确保路径有效。

有什么想法吗?谢谢。

4

2 回答 2

7

File.read没有模式或块的第二个参数,即File.open

contents_string = File.read(File.expand_path('lib/project_euler/' + filename))

请注意,您还可以编写:

contents = File.open(path).lines # returns a lazy enumerator, keeps the file open

或者:

contents = File.readlines(path) # returns an array, the file is closed.
于 2012-06-19T21:14:53.113 回答
1

File.read不需要该模式r- 您已经在File.read. 参数 foFile.read是 - 在文件名之后 - 偏移量和长度(这就是错误消息中预期为整数的原因)。

如果您需要该模式或(但也有- 选项),您可以提供模式,因为File.read(filename, :mode => 'r')这可能很有用。rbr:utf-8encoding

于 2012-06-19T21:29:43.457 回答