Ruby: Compare two arrays for matches, and order results in DESC order -


i have user model. each user has restaurant names associated them. have view (index.html.erb) shows users.

i want order users in view based on how many restaurants current_user , other user have in common in descending order... (it opposite!)


ex.

user1 (current_user) has been mcdonalds, burger king, arby's

user2 has been ivar's

user3 has been mcdonalds, burger king


when user1 loads index view, order users should displayed is:

user1 (3/3 restaurants match)

user3 (2/3 restaurants match)

user2 (0/3 restaurants match)


my user.rb file

def compare_restaurants   self.restaurants.collect end 

my users_controller.rb

def index   @users = user.all.sort_by {|el| (el.compare_resturants & current_user.compare_resturants).length } end 

if you're dead set on using sort_by can negate numbers:

def index   @users = user.all.sort_by { |el|     -(el.compare_resturants & current_user.compare_resturants).length   } end 

this trick works because you're sorting numeric values. if sorting on strings you'd have use this:

reverse_sorted = a.sort_by { |x| something(x) }.reverse 

but involve copy of array , work reverse do. in such cases should use full sort reversed comparison logic.

if you're trying use sort_by avoid computing expensive each comparison , sorting on non-numeric, use sort explicit schwartzian transform compute expensive things once.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -