Last active
December 14, 2015 14:08
-
-
Save CodeAbstract/5098182 to your computer and use it in GitHub Desktop.
Defining operators as if they were ordinary methods using the append (<<) and spaceship operator (<=>) operator
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
Sample code: Append Operator(<<) | |
class Inbox | |
attr_reader :unread_count | |
def initialize | |
@messages = [] | |
@unread_count = 0 | |
end | |
def <<(msg) | |
@unread_count += 1 | |
@messages << msg | |
return self | |
end | |
end | |
Sample Usage: | |
>> i = Inbox.new | |
=> #<Inbox: @messages=[], @unread_count=0> | |
>> i << "foo" << "bar" | |
=> #<Inbox: @messages=["foo", "bar", "baz"], @unread_count=3> | |
>> i.unread_count | |
=> 2 | |
Good habit: | |
Have your << method return the object itself, so the calls can be chained | |
Code: Spaceship Operator(<=>) | |
class Tree | |
include Comparable | |
attr_reader :age | |
def initialize(age) | |
@age = age | |
end | |
def <=>(other_tree) | |
age <=> other_tree.age | |
end | |
end | |
Usage: | |
>> a = Tree.new(2) | |
=> #<Tree:0x5c9ba8 @age=2> | |
>> b = Tree.new(3) | |
=> #<Tree:0x5c7fb0 @age=3> | |
>> c = Tree.new(3) | |
=> #<Tree:0x5c63b8 @age=3> | |
>> a < b | |
=> true | |
>> b == c | |
=> true | |
>> c > a | |
=> true | |
>> c != a | |
=> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment