下面是一个哈希值,我将其保存到文件中供以后阅读。从磁盘上的文件中读取哈希值
my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}
当我去读它时,是我的问题所在。 (下面的代码是从顶部分开)
my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
是nil
弄乱我的code..not知道如何其余摆脱如果。只是为了清晰起见,其余代码...
back_up_hash = {-1 => 20}
if my_hash.nil?
my_hash = back_up_hash
end
那个小nil
总是让my_hash等于back_up_hash。我需要.nil?
以防万一文件没有散列,否则问题会进一步下移。
我也试着阅读(啜食?..它是一个小文件)这样的文件....
my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.
我不熟悉Ruby,但我很肯定你必须将对象序列化到一个文件,而不是只写数据结构表示。如果我不得不猜测,我会说这是你的问题的一部分。 –
您可能有兴趣使用['Marshal'模块](https://ruby-doc.org/core-2.2.2/Marshal.html)将本地Ruby对象转储到磁盘并在以后快速加载它们。 – Phrogz
@用户。是的,该线程对我来说确实有一个可行的答案......我之前就看到了它。不幸的是,我有点不知所措,如果答案对我的情况来说不太理想,它会让我失望。感谢您指出该链接。元帅看起来是一个很好的解决方案。 – melee