Multilevel hash

Discussion in 'Ruby' started by aartist, May 25, 2005.

  1. aartist

    aartist Guest

    aartist, May 25, 2005
    #1
    1. Advertising

  2. aartist ha scritto:
    > With perl it's easy to write:
    >
    > $Q{$date}{$song_played} += 1
    >
    > How I can accomplish the same thing with ruby?
    >
    > Thanks!
    >
    > http://pleac.sourceforge.net/pleac_ruby/index.html didn't help much
    > here.
    >


    >> q={'key'=>{'key2'=>1}}

    => {"key"=>{"key2"=>1}}
    >> q['key']['key2']+=1

    => 2
    >> q['key']['key2']

    => 2
     
    gabriele renzi, May 25, 2005
    #2
    1. Advertising

  3. aartist wrote:
    > With perl it's easy to write:
    >
    > $Q{$date}{$song_played} += 1
    >
    > How I can accomplish the same thing with ruby?
    >
    > Thanks!
    >
    > http://pleac.sourceforge.net/pleac_ruby/index.html didn't help much
    > here.
    >


    irb(main):001:0> mh = Hash.new {|h,k| h[k] = {} }
    => {}
    irb(main):002:0> mh[1][2] = 3
    => 3
    irb(main):003:0> mh
    => {1=>{2=>3}}

    You can also do variable-level hashing:

    irb(main):006:0> pr = proc {|h,k| h[k] = Hash.new(&pr) }
    => #<Proc:0x4021eb08@(irb):6>
    irb(main):007:0> vh = Hash.new(&pr)
    => {}
    irb(main):008:0> vh[1][2][3][4] = 5
    => 5
    irb(main):009:0> vh
    => {1=>{2=>{3=>{4=>5}}}}

    (This is ruby-talk folklore!)
     
    Joel VanderWerf, May 25, 2005
    #3
  4. Joel VanderWerf wrote:
    > aartist wrote:
    >
    >> With perl it's easy to write:
    >>
    >> $Q{$date}{$song_played} += 1
    >>
    >> How I can accomplish the same thing with ruby?
    >>
    >> Thanks!
    >>
    >> http://pleac.sourceforge.net/pleac_ruby/index.html didn't help much
    >> here.
    >>

    >
    > irb(main):001:0> mh = Hash.new {|h,k| h[k] = {} }
    > => {}
    > irb(main):002:0> mh[1][2] = 3
    > => 3
    > irb(main):003:0> mh
    > => {1=>{2=>3}}


    And if you want automatic zeros:

    irb(main):010:0> mh0 = Hash.new {|h,k| h[k] = Hash.new(0)}
    => {}
    irb(main):011:0> mh0[1][2] += 1
    => 1
    irb(main):012:0> mh0
    => {1=>{2=>1}}
     
    Joel VanderWerf, May 25, 2005
    #4
    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. Sakcee
    Replies:
    1
    Views:
    307
    Ben Cartwright
    Mar 14, 2006
  2. virendra
    Replies:
    0
    Views:
    1,120
    virendra
    Aug 9, 2006
  3. rp
    Replies:
    1
    Views:
    539
    red floyd
    Nov 10, 2011
  4. PerlFAQ Server
    Replies:
    0
    Views:
    194
    PerlFAQ Server
    Jan 27, 2011
  5. PerlFAQ Server
    Replies:
    0
    Views:
    94
    PerlFAQ Server
    Mar 15, 2011
Loading...

Share This Page