Skip to content

Instantly share code, notes, and snippets.

@timtrautmann
Created October 12, 2009 18:25
Show Gist options
  • Save timtrautmann/208602 to your computer and use it in GitHub Desktop.
Save timtrautmann/208602 to your computer and use it in GitHub Desktop.
Defining operators by defining methods
# 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