1

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

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

我想创建哈希:

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

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

4

2 回答 2

4
hash = Hash[open("file.txt").lines.map do |line|
  key, value = line.split("=").map(&:strip)
  [key.to_sym, value]
end]
于 2012-07-24T19:57:48.437 回答
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
于 2012-07-24T20:12:14.703 回答