使用写入抛出 "No implicit conversion of String into Integer" 打开文件

Open file with write throws "No implicit conversion of String into Integer"

自从我上次在 Ruby 中编写代码以来已经有一段时间了(Ruby 2 是新的,哇,已经是 3 了),所以我觉得自己像个白痴。

我有一个只包含单词的文本文件:

hello

我的 ruby 文件包含以下代码:

content = File.read("test_file_str.txt","w")
puts content

当我 运行 它时,我得到:

`read': no implicit conversion of String into Integer (TypeError)

我以前从来没有遇到过这种情况,但是我写代码已经有一段时间了,所以很清楚PEBKAC。

然而,当我 运行 这个没有 ,"w" 时,一切似乎都很好。我做错了什么?

ruby 3.0.3p157(2021-11-24 修订版 3fb7d2cadc)[x64-mingw32]

根据文档,File.read 的第二个参数是要从给定文件中读取的字节长度,它是一个整数。

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

因此,在您的情况下,错误发生是因为您传递的参数必须是整数。它没有在 File.read 的文档中说明这一点,但它在 File#read:

中说明了这一点

Reads length bytes from the I/O stream.

length must be a non-negative integer or nil.

如果要指定模式,可以使用mode选项:

File.read("filename", mode: "r") # "r" or any other
# or
File.new("filename", mode: "r").read(1)

打开文件进行读取不接受写入模式

一般来说,以写入模式打开文件句柄进行读取是没有意义的。因此,您需要将方法重构为:

content = File.read("test_file_str.txt")

或者也许:

content = File.new("test_file_str.txt", "r+").read

具体取决于您要执行的操作。

另请参阅:IO#new 中的文件权限

Ruby 3.0.3 中的文件文档将您指向 IO#new 以获得可用的模式权限。如果您没有看到您正在寻找的选项,您可以去那里看看。