Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

How does the code for the comparable module work?

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)

To call a method, you refer to it by its name. In this case, the method name is <=>. I don't see this listed anywhere in the code, so I'm really confused as to how the last two lines of this code work,

2 Answers

Ari Misha
Ari Misha
19,323 Points

Hiya Yan! To understand this whole concept , you're gonna have to dive deep in module part of Ruby and how mixin and "include" keyword works. So in short, when you "include" module in a class, the module pretty much dumps its method in the class as "instance methods". Thats exactly whats been happening behind the scenes here. If you check out the rdocs for "comparable" module, it says that you're gonna have to define "<=>" operator.

The "<=>" operator is made of "<"(less than), "="(assignment) and ">" (greater than) operator. And the "<=>" method takes an argument "other_player" which happens to be an another object. So when you compare multiple objects initialized on "Player" class, you're pretty much calling the public "<=>" method you defined in Player class.

I hope it helped. (:

I still don't understand how it gets called. To call it you use the method name. I don't see the method name being used anywhere in the code.

Ari Misha
Ari Misha
19,323 Points

Hiya again! The comparable operators "<", ">" and "=" are method names. And you literally are calling it in your file in the last lines of codes.