我使用ruby 1.9.3-p194
使用以下代码收到警告if (x = true)
puts 'it worked'
end
# => warning: found = in conditional, should be ==
但是,如果我分配一个数组,则没有警告
if (x = [true])
puts 'it worked'
end
# => 'it worked', then returns nil since return of 'puts' is nil
为什么使用字符串会导致警告?或者也许是一个更好的问题,为什么使用数组不会引起警告?
答案 0 :(得分:4)
Ruby在分配时报告警告(文字:Fixnum,符号,字符串),nil和true / false
红宝石1.9.3-P194
parse.c:15026
static int
assign_in_cond(struct parser_params *parser, NODE *node)
{
switch (nd_type(node)) {
case NODE_MASGN:
yyerror("multiple assignment in conditional");
return 1;
case NODE_LASGN:
case NODE_DASGN:
case NODE_DASGN_CURR:
case NODE_GASGN:
case NODE_IASGN:
break;
default:
return 0;
}
if (!node->nd_value) return 1;
switch (nd_type(node->nd_value)) {
case NODE_LIT:
case NODE_STR:
case NODE_NIL:
case NODE_TRUE:
case NODE_FALSE:
/* reports always */
parser_warn(node->nd_value, "found = in conditional, should be ==");
return 1;
case NODE_DSTR:
case NODE_XSTR:
case NODE_DXSTR:
case NODE_EVSTR:
case NODE_DREGX:
default:
break;
}
return 1;
}
答案 1 :(得分:2)