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. Advertising

  2. On 11.08.2011 11:40, zak wrote:
    > 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

    --
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
    Robert Klemme, Aug 11, 2011
    #2
    1. Advertising

  3. zak

    zak Guest

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

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. rp
    Replies:
    1
    Views:
    494
    red floyd
    Nov 10, 2011
  2. Anthony Martinez
    Replies:
    4
    Views:
    259
    Robert Klemme
    Jun 11, 2007
  3. Michal Suchanek
    Replies:
    6
    Views:
    215
    Nobuyoshi Nakada
    Jun 13, 2007
  4. Srijayanth Sridhar
    Replies:
    19
    Views:
    596
    David A. Black
    Jul 2, 2008
  5. Replies:
    11
    Views:
    178
    Eric Schwartz
    Oct 10, 2005
Loading...

Share This Page