<分区>
这是我保存到文件中供以后读取的哈希值。
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
搞乱了我的代码的其余部分..不知道如何摆脱 if。为清楚起见,其余代码...
back_up_hash = {-1 => 20}
if my_hash.nil?
my_hash = back_up_hash
end
那个小nil
总是使 my_hash 等于 back_up_hash。我需要那个 .nil?
以防万一文件没有哈希,否则问题只会被推得更深。
我也试过像这样读取(slurp?..它是一个小文件)文件......
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.