Hash counting

M

Martin DeMello

Here is your problem. Hash.new(0) means "when I query the hash, and
the key I request is not in there, return 0". It does not actually add
{key =3D> 0} to the hash itself.

This is true, but counts[d] +=3D 1 is actually counts[d] =3D counts[d] + = 1
so the RHS will evaluate to 1 the first time, assigning it to the hash:

Oops - yes, missed that.

martin
 
J

Julian Leviston

Or square bracket method

Hash[1,2,3,4] # => {1 => 2, 3 => 4}

Blog: http://random8.zenunit.com/
Learn rails: http://sensei.zenunit.com/

counts = Hash.new(0)
eventdateID.each {|d| counts[d] += 1}

Here is your problem. Hash.new(0) means "when I query the hash, and
the key I request is not in there, return 0". It does not actually add
{key => 0} to the hash itself. To do that, you need the block form of
Hash.new, which yields as block the hash itself and the key:

counts = Hash.new {|h, k| h[k] = 0}

irb(main):001:0> a = Hash.new(0)
=> {}
irb(main):002:0> b = Hash.new {|h,k| h[k] = 0}
=> {}
irb(main):003:0> a['hello']
=> 0
irb(main):004:0> b['hello']
=> 0
irb(main):005:0> a
=> {}
irb(main):006:0> b
=> {"hello"=>0}

martin
 

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,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top