Ruby 新人刚学 ruby,遇到个问题诚心求教 [已解决]

areosome · 2012年01月21日 · 最后由 congteng 回复于 2012年02月04日 · 2593 次阅读

刚开始接触 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 的源码我也不太看得明白,只好上来请教了,希望能有牛人指点一下,若能详细一些最好,谢谢了!

看你的逻辑,ChineseNumber 初始化后需要调用下 to_num。

你需要引入 module Comparable ,不然它是不知道怎么比较的 . 在 class 定义下,加上 include Comparable

The Comparable mixin is used by classes whose objects may be ordered. The class must define the <=> operator, which compares the receiver against another object, returning -1, 0, or +1 depending on whether the receiver is less than, equal to, or greater than the other object. If the other object is not comparable then the <=> operator should return nil. Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >) and the method between?.

#2 楼 @weihuilee 嗯,确实就是这个原因,谢谢!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号