字符串/范围比较问题 [英] String/Range comparison problem
问题描述
这对于诸如
irb(main):001:0> ["b", "aa", "d", "dd"].sort
=> ["aa", "b", "d", "dd"]
但不是:
irb(main):002:0> ("B".."AA").each{ |x| print "#{x}," }
=> "B".."AA"
应产生: B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z, AA,=>"B" .."AA"但"B">"AA" =>是
should produce : B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,=> "B".."AA" but "B" > "AA" => true
与"B" .."BA"不同("B">"BA" => false):
Unlike "B".."BA" ("B" > "BA" => false) :
irb(main):003:0> ("B".."BA").each{ |x| print "#{x}," }
B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO,AP,AQ,AR,AS,AT,AU,AV,AW,AX,AY,AZ,BA,=> "B".."BA"
是否有任何使"b" .."aa"在红宝石中正常工作的建议?
Any advice to make "b".."aa" work as expected in ruby ?
我用
- irb 0.9.5(05/04/13)红宝石1.8.7
- (2009-06-12补丁程序级别174)[i486-linux]
- Linux 2.6.31-19-generic#56-Ubuntu SMP Thu Jan 28 01:26:53 UTC 2010 i686 GNU/Linux
推荐答案
做到这一点的最佳方法是将String子类化并重新定义比较运算符以满足您的需求.然后使用您的新类来确定范围.
The best way to do this is to subclass String and redefine the comparison operator to meet your needs. Then use your new class to make the range.
class MyString < String
def initialize str=""
super str
end
def <=>(other)
length_cmp = self.length <=> other.length
return length_cmp unless length_cmp == 0
super other
end
end
现在,您可以确保一列出现在另一列之前.
Now you can ensure that a column appears before another.
"b" < "aa" #=> false
MyString.new("b") < MyString.new("aa") #=> true
NB :只有任何比较运算符左侧的字符串都必须属于MyString类:
N.B.: Only the string on the left side of any comparison operator needs to be of class MyString:
MyString.new("b") < "aa" #=> true
"aa" > MyString.new("b") #=> false
这篇关于字符串/范围比较问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!