Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
Lian Maung
4,611 Points0 Answers
-
MICHAEL P
5,191 Points1 Answer
-
Patrick Shushereba
10,911 Points2 Answers
-
Augustine von Trapp
9,060 Points0 Answers
View all discussions for this video
Related 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