Jason Frankovitz
2006-Jun-28 21:22 UTC
[Rails] 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 Frankovitz - jason@seethroo.us - http://www.seethroo.us/ work: (310) 601-8454 cell: (415) 254-4890 AIM/Skype: jfrankov
Ezra Zygmuntowicz
2006-Jun-28 21:29 UTC
[Rails] hash value won''t increment with =+ operator
On Jun 28, 2006, at 2:22 PM, Jason Frankovitz wrote:> hash[b.id] =+ 1hash[b.id] += 1 -Ezra -------------- next part -------------- An HTML attachment was scrubbed... URL: http://wrath.rubyonrails.org/pipermail/rails/attachments/20060628/6f7e10b8/attachment.html
Rimantas Liubertas
2006-Jun-28 21:43 UTC
[Rails] hash value won''t increment with =+ operator
> 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] = xdid 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/