Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created October 27, 2012 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/3965711 to your computer and use it in GitHub Desktop.
Save havenwood/3965711 to your computer and use it in GitHub Desktop.
Refining Array's Spaceship Operator
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