Hash increment value

I have a bunch of posts that have category tags. I am trying to figure out how many times each category has been used.

I use rails with mongodb, BUT I don't think I need to get the appearance of categories from db, so the mongo part doesn't matter.

This is what I still have

@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

message structure

{"_id": ObjectId ("idnumber"), "created_at": "Tue Aug 03 ...", "categories": ["world", "sports"], "message": "the text of the post" , "poster_id": ObjectId ("idOfUserPoster"), "voters": []}

I am open to suggestions on how else to get the category count, but in the end I would like to get the number of voters, so it seems to me that the best way is to increase the number of hash_ categories and then add the .length voters, but one thing at a time, I just I'm trying to figure out how to increase the values ​​in the hash.

+3
source share
2 answers

/, , , /, :

@categories_hash = Hash.new(0)
current_user.recent_posts.each do |post|
  post.categories.each do |category|
    @categories_hash[category] += 1
  end
end
+7

mongodb, - map/reduce. Mongodb / JavaScript. / (), .. ( ).

, , ( ). "", ()

map 1 :

function () {
  if (this.tags) {
    this.tags.forEach(function (tag) {
      emit(tag, 1);
    });
  }
}

:

function (key, values) {
  var total = 0;
  values.forEach(function (v) {
    total += v;
  });
  return total;
}

, , . :.

{ 'rails' => 5, 'ruby' => 12, 'linux' => 3 }
+1

Source: https://habr.com/ru/post/1758113/


All Articles