ruby - 尝试在 Ruby 中打开文件 - 获取类型错误 : can't convert String into Integer

标签 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
    contents
  end

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

有什么想法吗?谢谢。

最佳答案

File.read模式和 block 都没有第二个参数,即 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.

关于ruby - 尝试在 Ruby 中打开文件 - 获取类型错误 : can't convert String into Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109440/

相关文章:

java - 按照原样将字符串写入文件中

c++ - lambda 函数的类型,使用 auto

ruby-on-rails - 在网络应用程序中使用开源代码/软件

css - Vue2导入css文件

ruby - 在 Ruby on Rails 中定义 ActiveRecord 方法以处理不同的 ActiveRecord 关系

c++ - 更改二进制文件

scala f 有界类型解释

c# - 'result is T' 与 'typeof(T).IsInstanceOfType(result)' 之间有显着差异吗?

ruby - Ruby On Rails 中的 Elasticsearch 从 0.90 升级到 2.x

ruby - 为什么这条线会抛出条件存在的错误?