Created
May 26, 2013 08:45
-
-
Save Olgagr/5652117 to your computer and use it in GitHub Desktop.
Defining case statement behaviour for Ruby class
This file contains 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
# to do it we have to define === method inside our class | |
class Ticket | |
attr_accessor :venue, :date, :price | |
def initialize(venue, date, price) | |
self.venue = venue | |
self.date = date | |
self.price = price | |
end | |
def ===(other_ticket) | |
self.venue == other_ticket.venue && self.date == other_ticket.date | |
end | |
end | |
# how to use | |
ticket1 = Ticket.new 'Town Hall', '01/01/2013', 50 | |
ticket2 = Ticket.new 'Town Hall', '01/01/2013', 100 | |
ticket3 = Ticket.new 'CMD', '01/02/2013', 50 | |
case ticket2 | |
when ticket2 then puts 'ticket 1 and ticket 2 are the same.' | |
when ticket3 then puts 'ticket 1 and ticket 3 are the same.' | |
else puts 'No match.' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment