Hash value won't increment with =+ operator

I have a database of bookmarks and tags, and want to count the number
of bookmarks each tag is assigned to, for example: user “tyler” has
the tag “concerts” on 15 out of his 30 bookmarks. This code:

hash = Hash.new(“0”); @user.tags.each do |t|
@user.bookmarks.each do |b|
x = 0
if b.tags.include?(t) then
hash[b.id] =+ 1
puts “hash is #{hash} & #{t.name} is on bkmk #{b.name}”
end
end
end

…results in this output:

hash is 195=>1 (80s is on bkmk 80s Video Clips)
hash is 195=>1 (culture is on bkmk 80s Video Clips)
hash is 195=>1 (music is on bkmk 80s Video Clips)
hash is 195=>1,196=>1 (activism is on bkmk Unemployment: A National
Obligation)
hash is 195=>1,196=>1 (careers is on bkmk Unemployment: A National
Obligation)
hash is 195=>1,196=>1 (eonomics is on bkmk Unemployment: A National
Obligation)
hash is 195=>1,196=>1 (politics is on bkmk Unemployment: A National
Obligation)
hash is 195=>1,196=>1 (social is on bkmk Unemployment: A National
Obligation)
hash is 195=>1,196=>1 (unemployment is on bkmk Unemployment: A
National Obligation)

The hash should end up as “195 => 3, 196 => 6” (3 tags on id 195, 6
tags on id 196) but it won’t do the hash[b.id] =+ 1 for some reason.
I also tried doing it this way:
if b.tags.include?(t) then hash[b.id] = x; x = x + 1; hash[b.id] = x
…but got the exact same output.

Any advice about what I’m missing here would be great. Thanks!

-Jason

Jason F. - [email protected] - http://www.seethroo.us/
work: (310) 601-8454
cell: (415) 254-4890
AIM/Skype: jfrankov

On Jun 28, 2006, at 2:22 PM, Jason F. wrote:

hash[b.id] =+ 1

hash[b.id] += 1

-Ezra

hash[b.id] =+ 1
hash[b.id] += 1

And if you wonder why

if b.tags.include?(t) then hash[b.id] = x; x = x + 1; hash[b.id] = x

did not work, it’s because of the first hash[b.id] = x – by doing
this you reset hash[b.id] to 0.
You have probably ment x = hash[b.id]; x = x + 1; hash[b.id] = x.

Anyway, Ezra has already provided you with a fix.

Regards,
Rimantas

http://rimantas.com/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs