On Thu, 13 Dec 2001, Harry Ohlsen wrote:

> In article <005801c18307$0fab2a50$eaa0a118@credenza>, "Bill Kelly"
> <billk / cts.com> wrote:
>
> >
> >     counts = Hash.new(0)
> >     text.scan(/[A-Z]/).each {|c| counts[c] += 1}
>
> The only problem with this is that I'm pretty sure that I was unable to
> do the += unless counts[c] already existed (which makes sense, since
> otherwise it's nil).  That makes the code messier, because you need a
> test.
>
> Am I wrong?  If not, can you see a neat way to get it to work, without
> using the test?

You are wrong ... The (0) after the Hash.new is significant see
http://www.rubycentral.com/book/ref_c_hash.html#new.  Here's an irb
transcript:

$ irb
irb(main):001:0> c1 = Hash.new
{}
irb(main):002:0> c2 = Hash.new(0)
{}
irb(main):003:0> c1['x'] += 1
NameError: undefined method `+' for nil
        from (irb):3
irb(main):004:0> c2['x'] += 1
1
irb(main):005:0> c2['banana']
0
irb(main):006:0>

Hope this helps,

Mike

-- 
mike / stok.co.uk                    |           The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/       | GPG PGP Key      1024D/059913DA
mike / starnix.com                   | Fingerprint      0570 71CD 6790 7C28 3D60
http://www.starnix.com/            |                  75D2 9EC4 C1C0 0599 13DA