simply says: Compares symbol with other_symbol after calling to_s on each of the symbols. Returns -1, 0, +1 or nil depending on whether symbol is less than, equal to, or greater than other_symbol.
nil
is returned if the two values are incomparable.
我试图返回nil
时了解Symbol#<=>
作品。这样我打的代码:
>> :x.to_s
=> "x"
>> 'x'.to_s
=> "x"
从上面的IRB
代码我想返回值将是0
。但实际是nil
。由于doc说在使用<=>
运算符to_s
之前应用RHO
和LHO
。但在这里,下面的代码不支持这个原则,在我看来。
>> :x <=> "x"
#=> nil
于是,我就看到源代码,来回答自己:
static VALUE
sym_cmp(VALUE sym, VALUE other)
{
if (!SYMBOL_P(other)) {
return Qnil;
}
return rb_str_cmp_m(rb_sym_to_s(sym), rb_sym_to_s(other));
}
查看源代码,很显然,如果RHO
不是Symbol
类的对象,nil
将返回。让我们来看看一些 更IRB:
>> "x" <=> :x
#=> nil
再次nil
。源代码说现在将执行rb_str_cmp_m(rb_sym_to_s(sym),rb_sym_to_s(other))
。所以现在我去看看STRING.C
的源代码。所以我们基本上是倾向于rb_str_cmp_m(???,"x")
。现在从github上发现了我:(?
手段不知道是什么值)
rb_str_cmp_m(VALUE str1, VALUE str2)
{
int result;
if (!RB_TYPE_P(str2, T_STRING)) {
VALUE tmp = rb_check_funcall(str2, rb_intern("to_str"), 0, 0);
if (RB_TYPE_P(tmp, T_STRING)) {
result = rb_str_cmp(str1, tmp);
}
else {
return rb_invcmp(str1, str2);
}
}
else {
result = rb_str_cmp(str1, str2);
}
return INT2FIX(result);
}
但上面的代码我不能understand.But我beleieve它有多么nil
正在生产的答案时LHO
不是对象类Symbol
。
任何人都可以帮助我了解nil
在LHO
是不是sym
?
仔细看看,是不是'rb_str_cmp_m(rb_sym_to_s(sym),rb_sym_to_s(other))' 'nil'是上面的行:'if(!SYMBOL_P(other)){return Qnil; }' – fmendez 2013-03-17 12:33:42
@fmendez是看得很清楚'other'是'RHO'。我正在谈论'LHO'。它首先检查'RHO'如果'sym'或不。如果'RHO'是'sym',那么它只是在'LHO和RHO'上调用'to_s'返回语句。 – 2013-03-17 12:35:31
也许你觉得<=>是一个运营商(因此你在谈论LHO和RHO)时感到困惑。这不是一个真正的操作符,而是一种方法(因此您应该谈论接收者和参数)。 LHO是接收器。我已经扩大了我的答案以澄清。 – AlexChaffee 2013-03-17 12:42:05