Ruby on rails File.read返回零
我用ruby创建了一个文件,并在其中保存了一些哈希。当我读文件时,我得到零。代码如下:Ruby on rails File.read返回零,ruby-on-rails,ruby,json,file,Ruby On Rails,Ruby,Json,File,我用ruby创建了一个文件,并在其中保存了一些哈希。当我读文件时,我得到零。代码如下: my_hash = Hash.new file = File.open("my_file.json", "w") my_hash["test_key"] = "0.1" file.write(my_hash.to_json) file_read = File.read("my_file.json") p file_read // This prints nil 当我打开文件时,我看到{“test_key
my_hash = Hash.new
file = File.open("my_file.json", "w")
my_hash["test_key"] = "0.1"
file.write(my_hash.to_json)
file_read = File.read("my_file.json")
p file_read // This prints nil
当我打开文件时,我看到{“test_key”:“0.1”}
我在这里遗漏了什么吗?您在写入文件后没有关闭该文件,因此在您尝试读取该文件时,操作系统很可能尚未将挂起的IO刷新到文件中。就操作系统而言,该文件尚不存在。完成写入后关闭该文件:
my_hash = Hash.new
file = File.open("my_file.json", "w")
my_hash["test_key"] = "0.1"
file.write(my_hash.to_json)
file.close # close after writing
file_read = File.read("my_file.json")
p file_read
啊哈。。。就这样。谢谢mcfinnigan!