刚开始接触 ruby,正在看 Ruby 完全自学手册这本书,照着上面一个例子写了小段代码,结果出来的效果却不一样,先贴一下代码(不长)
#coding:utf-8
class ChineseNumber
Numbers = ["一", "二", "三","四","五","六","七","八","九","十"]
attr :chinese_number
def initialize(value)
if Numbers.include?(value)
@chinese_number= value
else
raise "数字不正确!"
end
end
#转换为整数
def to_num
(Numbers.index(@chinese_number) + 1) if @chinese_number
end
def to_s
@chinese_number
end
def succ
raise(IndexError, "超出了数字范围!") if self.to_num >=10
ChineseNumber.new(Numbers[self.to_num])
end
def <=>(other)
(self.to_num) <=> (other.to_num)
end
end
def ChineseNumber(val)
ChineseNumber.new(val)
end
one=ChineseNumber("一")
four=ChineseNumber("四")
range=(one..four)
puts range.include?(ChineseNumber("三")) #问题就出在这里
按照书上的说法,用区间表示自定义对象的序列时,只要提供<=> 和 succ 方法,最后调用 include?时应该打印 true,可是结果却是输出 false,想不通是哪里不对了
google 了很久还是没有找到答案,文档里 include 的源码我也不太看得明白,只好上来请教了,希望能有牛人指点一下,若能详细一些最好,谢谢了!