Skip to content

Instantly share code, notes, and snippets.

@gregorymostizky
Created April 28, 2011 13:45
Show Gist options
  • Save gregorymostizky/946373 to your computer and use it in GitHub Desktop.
Save gregorymostizky/946373 to your computer and use it in GitHub Desktop.
Allows comparing arrays with nils
#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