write hash/array to file

Z

zak

Hi,

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

Thanks!
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top