Sturm
Sturm

Reputation: 4285

How can I create a dynamic hash from the contents of a file?

I don't have a specific purpose for this at the moment and the example I'm going to use definitely has better solutions (as this is unnecessary for something so simple) but I'd still like to see how this can be done. I'm wanting to populate a hash with dynamic symbols <-> content. Lets say I have a file that contains:

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

I'm wanting to create the hash:

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

I'm particular to it being symbols if it is possible, as I believe I've seen it done with variables. Since hash{variable => 'this'} would set the contents of variable as the key.

Upvotes: 1

Views: 1635

Answers (2)

knut
knut

Reputation: 27855

If you can define your own file format, you may vary a bit and use:

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

This is YAML-syntax.

You can load it very easy with:

require 'yaml'

filename = 'yourdatafile.txt'

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

This will make a Hash with strings. But a little modification in the data file gives you the symbols you want:

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

Upvotes: 1

tokland
tokland

Reputation: 67850

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

Upvotes: 4

Related Questions