Each of my users has an array of integers. The users attend a competition and I would like to sort them by the sum of the first 7 elements of their array. I know how to do each part individually, but I'm not sure how to put it together and display it in the show.
inside the def show
@competition.users.sort_by{|e| e.daily.first(7).sum}
for comp in @competition.users
p comp.name
p comp.daily #Their array
end
This is how I get the sum of the first 7 elements (currently used in my view):
user.daily.first(7).sum
thanks
This would sort the users in the descending order of their sum. User with highest sum will be in the top. Remove the - for ascending sort
@sorted_users = @competition.users.sort_by{|user| -user.daily.first(7).sum}
for comp in @sorted_users
p comp.name
p comp.daily #Their array
end
Or you can use sort_by! which will do inplace sorting
@competition.users.sort_by!{|user| -user.daily.first(7).sum}
for comp in @competition.users
p comp.name
p comp.daily #Their array
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With