Rails 4:TypeError - 没有将字符串隐式转换为整数

Rails 4:TypeError - no implicit conversion of String into Integer

我正在读取一个空的 HTML- 文件如下:

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

为什么会抛出这个 TypeError?

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,但仍然 "empty")。随着 Rails :

File.read(filename).blank?

要读取文件,您可以使用 rb 而不是 wb。

data = File.open("ur path","rb")