gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:37 25 4
gpt4 key购买 nike

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

解析.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 - 为什么在 if 条件下分配数组会导致警告而字符串不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12243568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com