Ruby 为什么在if条件下分配数组会导致警告,而字符串不会?

Ruby 为什么在if条件下分配数组会导致警告,而字符串不会?,ruby,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

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

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

Ruby在赋值(文本:Fixnum、Symbol、String)、nil和true/false时会报告警告

ruby-1.9.3-p194

if (x = true)
  puts 'it worked'
end

# => warning: found = in conditional, should be ==
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;
}

Ruby在赋值(文本:Fixnum、Symbol、String)、nil和true/false时报告警告

ruby-1.9.3-p194

if (x = true)
  puts 'it worked'
end

# => warning: found = in conditional, should be ==
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;
}
  • 您的两个程序都有相同的输出“它工作了”
  • 两个程序都使用赋值语句的值
  • 第一个使用一种模式,编译器认为该模式通常表示错误(因此出现警告)
  • 第二个使用的表达式(显然)过于复杂,无法触发警告消息
      • 您的两个程序都有相同的输出“它工作了”
      • 两个程序都使用赋值语句的值
      • 第一个使用一种模式,编译器认为该模式通常表示错误(因此出现警告)
      • 第二个使用的表达式(显然)过于复杂,无法触发警告消息

      我想你是说“它添加了一个警告”而不是“它不起作用”@user792445谢谢,你是对的我想你是说“它添加了一个警告”而不是“它不起作用”@user792445谢谢,你是对的