On Sep 3, 2009, at 10:00 AM, Josef Wolf wrote:
Hello,
In Ruby we generally use the standard YAML library for that. If you
don't need the content to be human readable, you could also use
Marshal, part of Ruby's core. Ruby 1.9 also ships with a JSON
library, which is available as a gem for Ruby 1.8.
Hope that helps.
James Edward Gray II
You might also be interested in the inspect method. It's what irb uses
to show the last value, but you can call it yourself to get a string
representation of standard data structures.
irb> my_hash_of_arrays = { 'fibs' => [ 0, 1, 1, 2, 3, 5, 8, 13 ],
'primes' => [ 2, 3, 5, 7, 11, 13, 17, 19 ], 'squares' => [ 1, 4, 9,
16 ] }
=> {"fibs"=>[0, 1, 1, 2, 3, 5, 8, 13], "squares"=>[1, 4, 9, 16],
"primes"=>[2, 3, 5, 7, 11, 13, 17, 19]}
irb> my_hash_of_arrays.inspect
=> "{\"fibs\"=>[0, 1, 1, 2, 3, 5, 8, 13], \"squares\"=>[1, 4, 9, 16],
\"primes\"=>[2, 3, 5, 7, 11, 13, 17, 19]}"
irb> puts my_hash_of_arrays.inspect
{"fibs"=>[0, 1, 1, 2, 3, 5, 8, 13], "squares"=>[1, 4, 9, 16],
"primes"=>[2, 3, 5, 7, 11, 13, 17, 19]}
=> nil
irb> p my_hash_of_arrays
{"fibs"=>[0, 1, 1, 2, 3, 5, 8, 13], "squares"=>[1, 4, 9, 16],
"primes"=>[2, 3, 5, 7, 11, 13, 17, 19]}
=> nil
You can also require the pretty print library.
irb> require 'pp'
=> true
irb> pp my_hash_of_arrays
{"fibs"=>[0, 1, 1, 2, 3, 5, 8, 13],
"squares"=>[1, 4, 9, 16],
"primes"=>[2, 3, 5, 7, 11, 13, 17, 19]}
=> nil
And you can get that value into your own string with the PP:
p method
(and a StringIO to collect the "output")
irb> require 'stringio'
=> true
irb> my_string = StringIO.new
=> #<StringIO:0x394234>
irb> PP:
p(my_hash_of_arrays, my_string)
=> #<StringIO:0x394234>
irb> my_string.rewind
=> 0
irb> my_string.read
=> "{\"fibs\"=>[0, 1, 1, 2, 3, 5, 8, 13],\n \"squares\"=>[1, 4, 9, 16],
\n \"primes\"=>[2, 3, 5, 7, 11, 13, 17, 19]}\n"
irb> my_string.rewind
=> 0
irb> puts my_string.read
{"fibs"=>[0, 1, 1, 2, 3, 5, 8, 13],
"squares"=>[1, 4, 9, 16],
"primes"=>[2, 3, 5, 7, 11, 13, 17, 19]}
=> nil
And all of this is part of Ruby's standard library.
-Rob
Rob Biedenharn
http://agileconsultingllc.com
(e-mail address removed)