Skip to content

Instantly share code, notes, and snippets.

@pricees
Created July 13, 2012 19:50
Show Gist options
  • Save pricees/3106997 to your computer and use it in GitHub Desktop.
Save pricees/3106997 to your computer and use it in GitHub Desktop.
Quick demo of overloading unary, binary operators.
############################
#
# The world is your oyster. Unless you overload it.
# Then it can be anything your heart desires.
#
# Very few operators can't be overloaded: and, or, not, &&, ||
#
class Person
attr_reader :my_bag
attr_accessor :name
def initialize(name = 'John Doe')
@name = name
end
# Binary
def +(person)
"#@name: Hello #{person.name}"
end
def -(person)
"#@name: Goodbye #{person.name}"
end
# Unary
def +@
"#@name: Hello world."
end
def -@
"#@name: Peace world."
end
# NOTE: I can overload ! but NOT 'not'...hinky.
def !
"#@name: What the fudge?!"
end
# Other
def []=(key, value)
@my_bag = "#@name found a #{key}, it reads: '#{value}'"
end
end
dude = Person.new "Ted"
dude1 = Person.new "John"
puts dude + dude1
# => Ted: Hello John
puts +dude
# => Ted: Hello world.
puts dude1 - dude
# => John: Goodbye Ted
puts -dude1
# => John: Peace world.
puts !dude
# => Ted: What the fudge?!
dude[:note] = "Booty on tap."
puts dude.my_bag
# => Ted found a note, it reads: 'Booty on tap.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment