[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

perl: $count{$element}++ in Ruby?

ngoc

6/17/2005 9:12:00 PM

Hi
what is $count{$element}++ in Ruby?
Have tried count[element] += 1 -> not work
and count[element] + 1 -> not work too
thanks
ngoc
3 Answers

James Gray

6/17/2005 9:25:00 PM

0

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



Glenn Parker

6/17/2005 9:30:00 PM

0

ngoc wrote:
> Hi
> what is $count{$element}++ in Ruby?
> Have tried count[element] += 1 -> not work

Really?

irb(main):001:0> count = []
=> []
irb(main):002:0> elem = 1
=> 1
irb(main):003:0> count[elem] = 0
=> 0
irb(main):004:0> count[elem] += 1
=> 1

--
Glenn Parker | glenn.parker-AT-comcast.net | <http://www.tetrafoi...


ngoc

6/17/2005 9:56:00 PM

0

my mistake is count = Hash.new() instead of Hash.new(0)
thanks very much
ngoc