write hash/array to file

Discussion in 'Ruby' started by zak, Aug 11, 2011.

  1. zak

    zak Guest

    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!
     
    zak, Aug 11, 2011
    #1
    1. Advertisements

  2. 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
     
    Robert Klemme, Aug 11, 2011
    #2
    1. Advertisements

  3. zak

    zak Guest

    Very helpful, thank you!
     
    zak, Aug 11, 2011
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.
Similar Threads
There are no similar threads yet.
Loading...