Created
October 12, 2009 18:25
-
-
Save timtrautmann/208602 to your computer and use it in GitHub Desktop.
Defining operators by defining methods
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
# The Well-Grounded Rubyist | |
# Chapter 7 Built-in essentials | |
# Section 7.2.1 Defining operators by defining methods | |
# | |
# The example in the book uses the += and -= shortcut operators inside of Account#+(x) | |
# and Account#-(x) | |
# | |
# The below seems to be the more correct way. | |
class Account | |
attr_accessor :balance | |
def initialize(amount = 0) | |
self.balance = amount | |
end | |
def +(x) | |
self.balance + x | |
end | |
def -(x) | |
self.balance - x | |
end | |
def to_s | |
balance.to_s | |
end | |
end | |
acc = Account.new(20) | |
# Should return 15 | |
acc - 5 | |
# Should print 20 | |
puts acc | |
# Should set self.balance to 15 | |
acc -= 5 | |
# Should print 15 | |
puts acc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment