Sorting list of objects by object attribute?

I have a list of objects that are pulled in from an API. Here is the snippet of output (as there’s about 300 lines):

 combo =>
 ID: 6, Name:Thomas Partey, Club:1, Position: 3, Price: $4.7, Total Pts: 57    
 ID: 7, Name:Martin Ødegaard, Club:1, Position: 3, Price: $7.0, Total Pts: 128    
 ID: 8, Name:Kieran Tierney, Club:1, Position: 2, Price: $4.6, Total Pts: 23    
 ID: 12, Name:Emile Smith Rowe, Club:1, Position: 3, Price: $5.6, Total Pts: 5 

I would like to change the order so that they are ranked by Total Points rather than ID

I have tried the following:

sorted = combo.sort_by(@totalpoints)

As well as: (but I assume I want to try and use @teampoints since I’ve defined that)

sorted = combo.sort_by(:totalpoints)

My Full code is:

class Player
    attr_accessor :id, :firstname, :secondname, :club, :position, :price, :totalpoints, 
:active
def initialize(id, firstname, secondname, club, position, price, totalpoints, active)
    @id = id.to_i
    @firstname = firstname.to_s
    @secondname = secondname.to_s
    @club = club.to_s
    @position = position.to_i
    @price = price / 10.to_f
    @totalpoints = totalpoints.to_i
    @active = active.to_i
end

def to_s()
    "  ID: " + @id.to_s + ", Name:" + @firstname.to_s + " " + @secondname.to_s + ", Club:" + @club.to_s + ", Position: " + @position.to_s + ", Price: $" + @price.to_s + ", Total Pts: " + @totalpoints.to_s + "    "
end

def self.pull()
    require 'net/http'
    require 'json'
    url = 'https://fantasy.premierleague.com/api/bootstrap-static/'
    uri = URI(url)
    response = Net::HTTP.get(uri)
    object = JSON.parse(response)
    elements = object["elements"]
    elements.map! { |qb|
        if  qb["chance_of_playing_next_round"].to_f > 0
            Player.new(
                qb["id"],                               # ID
                qb["first_name"],                       # First Name
                qb["second_name"],                      # Surname
                qb["team"],                             # Club
                qb["element_type"],                     # Position
                qb["now_cost"],                         # Current Price
                qb["total_points"],                     # Total Points
                qb["chance_of_playing_next_round"])     # Chance Of Playing
        end
    }
end


combo = Player.pull().map{|qb| qb}
sorted = combo.sort_by(@totalpoints)
puts sorted

end

>Solution :

Based on what you’ve got shown, this should do what you need:

sorted = combo.sort_by(&:totalpoints)

It’s essentially a shortened version of this:

sorted = combo.sort_by { |_combo| _combo.totalpoints }

Leave a Reply