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