Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图用Ruby打开文件-获取类型错误:can';t将字符串转换为整数_Ruby_File_Types - Fatal编程技术网

试图用Ruby打开文件-获取类型错误:can';t将字符串转换为整数

试图用Ruby打开文件-获取类型错误:can';t将字符串转换为整数,ruby,file,types,Ruby,File,Types,不确定这里发生了什么,或者在这种情况下,整数可能是什么。代码如下: 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 c

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

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
def build_array_from_文件(文件名)
内容=[]
File.read(File.expand_path('lib/project_euler/'+filename),'r')do|File|
而line=file.get
contents没有mode或block的第二个参数,即:

请注意,您还可以编写:

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

没有模式或块的第二个参数,即:

请注意,您还可以编写:

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


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


您可以将模式设置为
File.read(文件名:mode=>'r')
如果您需要模式
rb
r:utf-8
(但还有一个
编码
-选项)。

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


您可以将模式设置为
File.read(filename,:mode=>'r')
如果您需要模式
rb
r:utf-8
(但还有一个
编码
-选项)。

问题是
文件.open(path)。行
不会自动关闭返回的文件。您要查找的是
contents=File.open(path){| File | File.lines}
@MatheusMoreira:您有一点可以让文件保持打开状态。但请注意,如果您计划延迟访问,这是不可避免的。请尝试您的代码段,它应该返回
IOError:closed stream
,您不能在封闭的流上懒洋洋地读取。@MatheusMoreira
File.open(path,&:lines)
问题是
File.open(path)。lines
不会自动关闭返回的文件。您要查找的是
contents=File.open(path){| File | File.lines}
@MatheusMoreira:您有一点可以让文件保持打开状态。但请注意,如果您计划延迟访问,这是不可避免的。请尝试您的代码段,它应该返回
IOError:closed stream
,您不能在一个封闭的流上懒洋洋地读取。@MatheusMoreira
File.open(path,&:lines)
contents = File.readlines(path) # returns an array, the file is closed.