ruby-on-rails - rails 4 :TypeError - no implicit conversion of String into Integer

标签 ruby-on-rails ruby file ruby-on-rails-4 readfile

我正在读取一个空的 HTML 文件,如下所示:

file = File.read("file_path/file.html", "wb")

为什么会抛出这个类型错误?

no implicit conversion of String into Integer



日志:

Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)

TypeError (no implicit conversion of String into Integer):
  app/controllers/abc_controller.rb:49:in `read'
  app/controllers/abc_controller.rb:49:in `build'

最佳答案

如果文件为空,您到底想读取什么?

第二个参数为 File#read是可选的,应该是要从文件中读取的字符串的长度。 "wb" 不是整数,因此会出现错误消息。

您使用的参数看起来更像 open .

读取文件

如果你想读取文件,只需使用

content = File.read(filename)

写入文件

如果你想写的话可以使用

File.open(filename,'w+') do |file|
  file.puts "content"
end

'w+' 是一种文件模式:

Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

文件存在

如果您想检查文件是否存在:

File.exists?(filename)

文件是否为空?

如果您想检查现有文件是否为空:

File.size(filename)==0

文件可能充满空格(大小 > 0,但仍然“空”)。带 rails :

File.read(filename).blank?

关于ruby-on-rails - rails 4 :TypeError - no implicit conversion of String into Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090664/

相关文章:

file - 如何在 Go 中编写安全的重命名? (或者,如何在 Go 中编写这个 Python?)

ruby-on-rails - 使用 Rails 和设计基于 Ember.js session cookie 的身份验证

javascript - gem 'gon' - Quotes#index 中的名称错误,未初始化的常量 ActionView::CompiledTemplates::Gon,Rails 5

javascript - jQuery基于active切换侧边栏子菜单

ruby - 是否可以从父类创建子类的实例?

ruby - 每个功能前后是否有 cucumber 钩子(Hook)运行

java - 如果 imagefolder 的内容已更改,如何检查 java

ruby-on-rails - Rails 测试期间发生了什么?

ruby - 在 Ruby 中,计算数字 e 时出现意外结果

c - 如何写入空文件中的特定偏移量