i have a hash
h={"2011-01-01"=>[1,2,3], "2011-01-02"=>[2,3,4]}
how can i write this into a file having theis format:
2011-01-01 [1,2,3]
2011-01-02 [2,3,4]
I always end up with something like
2011-01-01 123
2011-01-02 234
In this particular case you can do
irb(main):001:0> h={"2011-01-01"=>[1,2,3], "2011-01-02"=>[2,3,4]}
=> {"2011-01-01"=>[1, 2, 3], "2011-01-02"=>[2, 3, 4]}
irb(main):002:0> h.sort.each do |d,l| printf "%s\t%p\n", d, l end
2011-01-01 [1, 2, 3]
2011-01-02 [2, 3, 4]
=> [["2011-01-01", [1, 2, 3]], ["2011-01-02", [2, 3, 4]]]
I don't like that approach because it relies on the implementation of
#inspect. If that is changed your output will change, too. I would
rather do something like
irb(main):006:0> h.sort.each do |d,l| printf "%s\t[%s]\n", d, l.join(',
') end
2011-01-01 [1, 2, 3]
2011-01-02 [2, 3, 4]
where you have control over the output format.
And I suggest you make your keys instances of Date and convert them when
reading and writing. This gives you all the methods of Date for
manipulating them. You can convert them via
irb(main):021:0> Date.strptime '2011-02-01', '%Y-%m-%d'
=> #<Date: 2011-02-01 (4911187/2,0,2299161)>
Kind regards
robert