我正在读取一个空的 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/