从磁盘上的文件读取哈希

1 ruby high-availability

这是我保存到文件中以供以后读取的哈希。

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}
Run Code Online (Sandbox Code Playgroud)

当我阅读它时,是我的问题所在。(以下代码与顶部分开)

my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
Run Code Online (Sandbox Code Playgroud)

nil弄乱了我其余的代码..不确定如何摆脱如果。为了清楚起见,其余代码...

back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end
Run Code Online (Sandbox Code Playgroud)

那一点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.
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以eval在字符串(source)上使用该方法

eval("{-1 => 20, -2 => 30, -3 => 40}")
=> {-1 => 20, -2 => 30, -3 => 40}
Run Code Online (Sandbox Code Playgroud)