我有一堆帖子裏面有分類標籤。 我想知道每個類別被使用了多少次。散列值遞增值
我正在使用mongodb導軌,但我不認爲我需要從db中獲取類別的出現,所以mongo部分應該沒有關係。
這是我迄今爲止
@recent_posts = current_user.recent_posts #returns the 10 most recent posts @categories_hash = {'tech' => 0, 'world' => 0, 'entertainment' => 0, 'sports' => 0} @recent_posts do |cat| cat.categories.each do |addCat| @categories_hash.increment(addCat) #obviously this is where I'm having problems end end end
後的結構
{"_id" : ObjectId("idnumber"), "created_at" : "Tue Aug 03...", "categories" :["world", "sports"], "message" : "the text of the post", "poster_id" : ObjectId("idOfUserPoster"), "voters" : []}
我願意就怎麼回事獲得類別的數量的建議,但我會希望最終得到選民的人數,所以在我看來,最好的辦法是增加categories_hash,然後添加elections.length,但是一次只能做一件事,我只是想弄清楚如何增加值在散列。
嗯,我一直在試圖學習和使用map/reduce,我認爲他們可能是一個更簡單的方法來做到這一點與紅寶石,但我會給你的方式一槍,並報告回來。 – pedalpete 2010-08-05 01:41:49
在Ruby中確實比較容易做到,但效率也不高,儘管它對於小型站點來說可能足夠了。我發佈了另一個與您的原始代碼的變體的答案。 – Zargony 2010-08-05 01:50:32