How can I store name/value pairs in a file with Ruby where the values can be also multiline text?

510 Views Asked by At

How can I store name/value pairs (also called hashes) in a file with Ruby where the values can be also multiline text? Of course I want to code the most simple way. I have seen such text files earlier in Windows:

[name]
Dr. Hash Mark

[biografy]
Bla bla bla
bla bla bla
bla bla bla

[works]
The big red one (1923)
The little black zero (1926)

Is there any library or gem for Ruby to handle this kind of files? Maybe I could use XML and the XMLSimple gem:

<man>
 <name>Dr. Hash Mark</name>
 <biografy>
  Bla bla bla
  bla bla bla
  bla bla bla
 </biografy>
 <works>
  The big red one (1923)
  The little black zero (1926)
 </works>
</man>

Both of them would be good for me, but I also need a handy application to fill in a bunch of this kind of text files with data, I have no clue which application to use to generate such text files which later will be readable with Ruby. I think of a relational database application - but I am not sure - in which I can define my data structure (the name, biografy, works) and then I get text fields to fill in with data, and then save the data in the given format in text files. Can anybody help me how to achieve this?

1

There are 1 best solutions below

2
On

YAML is a good choice, there is a lib for it in the stdlib, it is human readable/editable, it's fairly widely used (e.g. settings files in Rails), it supports multiline strings:

require 'yaml'

filename = 'hash.yaml'
original_hash = {'a' => 'b', 'c' => "d\ne"}
File.write filename, YAML.dump(original_hash)

puts "FILE LOOKS LIKE: #{File.read filename}"
puts "-" * 10

resulting_hash = YAML.load File.read(filename)
puts "READ BACK IN: #{resulting_hash.inspect}"

puts "ARE THEY THE SAME? #{original_hash == resulting_hash}"