为什么在if条件导致警告时分配数组而字符串不是?

时间:2012-09-03 07:22:34

标签: ruby

我使用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

为什么使用字符串会导致警告?或者也许是一个更好的问题,为什么使用数组不会引起警告?

2 个答案:

答案 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)

  • 你的两个程序都有相同的输出“它工作”。
  • 您的两个程序都使用赋值语句的值
  • 第一个使用编译器认为通常表示错误的模式(因此警告)
  • 第二个使用的表达式(显然)过于复杂而无法触发警告消息