Created
April 28, 2011 13:45
-
-
Save gregorymostizky/946373 to your computer and use it in GitHub Desktop.
Allows comparing arrays with nils
This file contains hidden or 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
#usage | |
a = [1,2] | |
b = [1,nil] | |
a.extend(ArrayWithNilCompareHack) | |
b.extend(ArrayWithNilCompareHack) | |
a<=>b # works | |
# code | |
module ArrayWithNilCompareHack | |
def <=>(other) | |
size_compare = self.size <=> other.size | |
return size_compare if size_compare.nonzero? | |
each_index do |i| | |
next if self[i].nil? && other[i].nil? | |
return -1 if self[i].nil? | |
return 1 if other[i].nil? | |
normal = self[i] <=> other[i] | |
next if normal==0 | |
return normal | |
end | |
0 | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment