Created
December 14, 2013 15:27
-
-
Save cowboy-cod3r/7960537 to your computer and use it in GitHub Desktop.
Ruby: Spaceship
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# == Description | |
# the <=> operator returns 1, 0, or -1, depending on the value of the left arugment relative to the right | |
# This operator is good to use when you want to define how to compare two like object | |
# The operator must return -1 for less than, 1 for greater than, and 0 for equal to | |
class Expense | |
# Modules | |
include Comparable | |
# Accessors | |
attr_accessor :amount | |
# ==== Description | |
# overwrite the spaceship operator | |
# When the method is evaluated, it compares the | |
# amount member of the current object to the | |
# amount member of the expense object passed in. | |
# It will return 1 for less than, 1 for greater than | |
# and 0 for equal to. | |
def <=>(expense) # You pass in an expense object | |
self.amount <=> expense.amount | |
end | |
end | |
expense1 = Expense.new() | |
expense2 = Expense.new() | |
expense1.amount = 1 | |
expense2.amount = 2 | |
puts expense1 <=> expense2 # returns -1 | |
expense1.amount = 1 | |
expense2.amount = 1 | |
puts expense1 <=> expense2 # returns 0 | |
expense1.amount = 2 | |
expense2.amount = 1 | |
puts expense1 <=> expense2 # returns 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment