James Gray
6/17/2005 9:25:00 PM
On Jun 17, 2005, at 4:15 PM, ngoc wrote:
> Hi
> what is $count{$element}++ in Ruby?
> Have tried count[element] += 1 -> not work
This is the right answer (or count[element] = count[element] + 1).
Perhaps you're asking about how to set the Hash to default to 0?
irb(main):001:0> count = Hash.new(0)
=> {}
irb(main):002:0> count[:whatever] += 1
=> 1
irb(main):003:0> count[:whatever] += 1
=> 2
irb(main):004:0> count[:whatever] += 1
=> 3
irb(main):005:0> count[:whatever] += 5
=> 8
irb(main):006:0> count[:something_else] += 1
=> 1
irb(main):007:0> count
=> {:whatever=>8, :something_else=>1}
Hope that helps.
James Edward Gray II