如何从文件内容创建动态哈希?

时间:2012-07-24 19:50:53

标签: ruby

我目前没有特定的目的,我将要使用的示例肯定有更好的解决方案(因为这对于这么简单的事情来说是不必要的)但是我仍然希望看到它如何能够完成。我想用动态符号填充哈希< - >内容。假设我有一个文件包含:

this = that
that = this
frog = taco
pota = to

我想创建哈希:

hash = { :this => 'that', :that => 'this', :frog => 'taco', :pota => 'to' }

如果可能的话,我特别注意它是符号,因为我相信我已经看到它用变量完成了。由于hash {variable => 'this'}将变量的内容设置为键。

2 个答案:

答案 0 :(得分:4)

hash = Hash[open("file.txt").lines.map do |line|
  key, value = line.split("=").map(&:strip)
  [key.to_sym, value]
end]

答案 1 :(得分:1)

如果您可以定义自己的文件格式,可能会有所不同并使用:

this: that
that: this
frog: taco
pota: to

这是YAML - 语法。

您可以通过以下方式轻松加载:

require 'yaml'

filename = 'yourdatafile.txt'

p YAML.load(File.read(filename))

这将使用字符串制作哈希。但是数据文件中的一些修改可以为您提供所需的符号:

:this: that
:that: this
:frog: taco
:pota: to