"ArgumentError: string contains null byte" when writing Marshalled data into a file

"ArgumentError: string contains null byte" when writing Marshalled data into a file

我有一个大数组,我想将其保存到文件中。但是当我发出:

File.write Marshal.dump(users),"users.txt"

我得到:

ArgumentError: string contains null byte
from (pry):201:in `write'

我用 JSON 和 YAML 也得到了相似的结果。我该怎么做才能从字符串中删除空字节?我尝试了 String#scrub 但没有帮助。

文件名和内容参数的顺序颠倒了。第一个参数必须是名称,第二个参数必须是内容。引发参数错误是因为 file names shouldn't contain null bytes.

并且由于您正在处理二进制数据,因此您应该使用 IO.binwrite:

File.binwrite "users.txt", Marshal.dump(users)