Reputation: 148
How can I create a big hash automatically and store it in a file?
The result should be like : => {:1=>10, :2=>10, :3=>10, ... :100=>10}
Upvotes: 1
Views: 148
Reputation: 160551
You haven't told us nearly enough to give specific recommendations, but, in general, you should look into using YAML to serialize the hash. YAML is a defined specification that makes it easy to store the data in a format easily read by people, and easily reused by other languages.
For instance, this is what a basic hash looks like when serialized:
require 'yaml'
hash = {'a' => 1, 'b' => 2}
puts hash.to_yaml
Running that code will output:
---
a: 1
b: 2
Because it's just a string being output, it's easy to write it to a file:
File.write('hash.yaml', hash.to_yaml)
Which, when run creates a file in my current directory containing the above output:
$ cat hash.yaml
---
a: 1
b: 2
I can reread the data and parse it back into a hash just as easily:
hash = YAML.load_file('hash.yaml')
# => {"a"=>1, "b"=>2}
I can modify the YAML file:
---
a: 1
b: 2
c: 3
and reload it and see the new element:
hash = YAML.load_file('hash.yaml')
# => {"a"=>1, "b"=>2, "c"=>3}
YAML is capable of serializing very complex arrays and hashes, and other languages can reuse that data. Objects get funky so it's always good to create your own to_a
or to_h
or to_yaml
methods which then output an array or hash so the YAML engine can correctly serialize them.
Ruby's YAML class only defines some of the methods. Psych is the underlying engine so its documentation is important also. For instance, I used load_file
to reload the file, and it's documented in the Psych documentation.
Upvotes: 1
Reputation: 106812
I would do that like this:
File.open('filename.txt', 'w') do |file|
file.write(Hash[(1..100).map { |i| [i, 10] }])
end
Upvotes: 1