Last active
December 31, 2015 11:39
-
-
Save u2/7981117 to your computer and use it in GitHub Desktop.
Nil compared with Numeric and String
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
# Allows `nil` to compare to String,Numeric,NilClass.So you can sort a array if it include nil. | |
# | |
# nil <=> '' # => 0 | |
# nil <=> 'Tom' # => -1 | |
# nil == '' # false | |
# For the NilClass the method == do not depond on the <=>. | |
# | |
# '' <=> nil # => 0 | |
# 'Tom' <=> nil # => 1 | |
# '' > nil # => false | |
# 'a' > nil # => true | |
# '' == nil # => false | |
# For the String the methods <,<=,>=,> depend on <=>,but the method == does not depend on <=>. | |
# | |
# 1 == nil # => false | |
# 1 <=> nil # => 1 | |
# | |
# ['c',nil,'a','b'].sort # => [nil, "a", "b", "c"] | |
# [2,nil,1,3,-2].sort # => [-2, nil, 1, 2, 3] | |
# | |
# CREDIT: u2 | |
# | |
# @deprecated It's not a good idea! | |
# It have some side effects. | |
# ['c',nil,'a','b'].sort_by{|i|i.to_s} | |
# => [nil, "a", "b", "c"] | |
class NilClass | |
def <=>(b) | |
alias compared <=> | |
case b.class.name | |
when 'String' then ''<=>(b) | |
when 'Float','Fixnum','Bignum' then 0<=>(b) | |
when 'NilClass' then 0 | |
else | |
compared(b) | |
end | |
end | |
end | |
class String | |
alias compared <=> | |
def <=>(b) | |
if b.is_a? NilClass | |
compared('') | |
else | |
compared(b) | |
end | |
end | |
end | |
[Fixnum,Float,Bignum].each do |numeric| | |
numeric.class_eval do | |
alias compared <=> | |
def <=>(b) | |
if b.is_a? NilClass | |
compared(0) | |
else | |
compared(b) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment