I changed how I was doing things but at one point I needed to append a string to the end of an array of strings and I wanted it guaranteed to be lexicologically after all of the other strings. For integers this would be MAXINT or some similar constant.
In my particular case, I'm using Ruby. I want some Ω such that "Ω" > "s" for all s.
CodePudding user response:
There's no such string satisfying that behavior. Such a string would have to be an infinite sequence of the largest Unicode codepoint, and strings in Ruby cannot be infinite.
However, we can always make a class for which we control the comparison operator.
class OmegaType
include Comparable
def <=>(other)
if other.is_a? OmegaType
0
else
1
end
end
end
Omega = OmegaType.new
And then, if we really want to, we can monkeypatch String
to agree with our assessment.
class String
alias old_cmp <=>
def <=>(other)
if other.is_a? OmegaType
-1
else
self.old_cmp other
end
end
end
Now, we find
puts(Omega > 'a') # true
puts('a' < Omega) # true
But is this good practice? Not really. It's probably best to go through whatever list of strings your actual program uses and just pick the "maximum" string to be your "after" value. Or pick something that works in your use case. For instance, if all the strings you're dealing with are alphanumeric, then pick a Unicode character larger than all alphanumerics.
CodePudding user response:
I really don't know if I can recommend this, but here is your constant:
LAST_STRING = "last" #or whatever
def LAST_STRING.<=>(other)
1
end
p ["a", "aaa", LAST_STRING, "z"].sort