Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
For our first stop on the Ruby Core Module tour, we're going to check out the `Comparable` module. The `Comparable` module allows you to make your classes sortable and gives you convenience methods.
Links
Code Samples
By including the Comparable
class and defining the spaceship operator( <=>
), we get access to comparison functionality in our classes:
class Player
include Comparable
attr_accessor :name, :score
def <=>(other_player)
score <=> other_player.score
end
def initialize(name, score)
@name = name
@score = score
end
end
player1 = Player.new("Jason", 100)
player2 = Player.new("Kenneth", 80)
puts "player1 > player2: %s" % (player1 > player2)
puts "player1 < player2: %s" % (player1 < player2)
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up