Created
October 27, 2012 19:04
-
-
Save havenwood/3965711 to your computer and use it in GitHub Desktop.
Refining Array's Spaceship 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
module SpaceshipArray | |
refine Array do | |
def <=> other | |
return 'equal' if self == other | |
1.upto [self.count, other.count].max do |i| | |
case self[i] <=> other[i] | |
when 1 | |
return 'bigger' | |
when -1 | |
return 'smaller' | |
end | |
end | |
end | |
end | |
end | |
[1,2,3] <=> [1,2,3] | |
#=> 0 | |
[1,2,4] <=> [1,2,3] | |
#=> 1 | |
[1,2,3] <=> [1,2,4] | |
#=> -1 | |
using SpaceshipArray | |
[1,2,3] <=> [1,2,3] | |
#=> "equal" | |
[1,2,4] <=> [1,2,3] | |
#=> "bigger" | |
[1,2,3] <=> [1,2,4] | |
#=> "smaller" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment