How to prevent the ranking from displaying more than one post by the same user

Asked 2 years ago, Updated 2 years ago, 35 views

I am creating a posting service, and in order to create a ranking, I created it in the following form:

@post_array=
{:post=>838, 
  —count=>6,
  —rank=>1,
  —user_id=>14},
 {:post=>837,
  —count=>4,
  —rank=>2,
  —user_id=>5},
 {:post=>835.
  —count=>2,
  —rank=>3,
  —user_id=>14}

post = ID of the post
count = the number of likes in a post
rank = ranking
user_id = ID of the user

In this ranking, I would like to display only the top 3 posts of the same user, but what should I do?

Thank you for your cooperation.

ruby

2022-09-30 16:18

2 Answers

I have defined this method (function).

def limit_by_user(post_array, maximum)
  memo = Hash.new { | h,k | h[k] = 0}
  post_array
    .sort_by {|post|post[:rank]}
    .select {|post|
      user_id=post[:user_id]
      (memo[user_id]+=1)<=maximum
    }
end

Here are the results:

@post_array=[
  {:post=>838,:count=>6,:rank=>1,:user_id=>14},
  {:post=>837,:count=>4,:rank=>2,:user_id=>5},
  {:post=>835,:count=>9,:rank=>3,:user_id=>14},
  {:post=>904,:count=>8,:rank=>4,:user_id=>14},
  {:post=>905,:count=>7,:rank=>5,:user_id=>14},
  {:post=>906,:count=>6,:rank=>6,:user_id=>5},
]

puts limit_by_user(@post_array,3)

# execution result
{:post=>838,:count=>6,:rank=>1,:user_id=>14}
{:post=>837,:count=>4,:rank=>2,:user_id=>5}
{:post=>835,:count=>9,:rank=>3,:user_id=>14}
{:post=>904,:count=>8,:rank=>4,:user_id=>14}
{:post=>906,:count=>6,:rank=>6,:user_id=>5}

However, if these data are stored in a database, SQL filtering may be more efficient than Ruby.


2022-09-30 16:18

Instead of relying on rails, why don't we prepare a work table or something that extracts the top three items of each user before sorting them?


2022-09-30 16:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.