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

N

ngoc

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

James Edward Gray II

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
 
G

Glenn Parker

ngoc said:
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
 

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

Forum statistics

Threads
474,173
Messages
2,570,939
Members
47,484
Latest member
JackRichard

Latest Threads

Top