||= 条件赋值运算符的官方扩展 [英] Official expansion of ||= conditional assignment operator

查看:50
本文介绍了||= 条件赋值运算符的官方扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强调的是,我正在寻找 ||= 运算符被 Ruby 1.9.3 解释器扩展的实际方式,而不是它的显示方式 根据其行为进行扩展.我真正希望的是能够找到实际解释器来源的人,遗憾的是,我可能无法胜任这项任务.我发现似乎检查这个问题的唯一资源已经过时:短路(||=)边缘情况".

I want to emphasize I am looking for the actual way the ||= operator is expanded by the Ruby 1.9.3 interpreter, not how it appears to be expanded based on its behavior. What I'm really hoping for is someone who has grokked the actual interpreter source, a task which I sadly am probably not up to. The only resource I have found that appears to examine this question is out of date: "A short-circuit (||=) edge case".

我上面提到的资源似乎暗示了 x ||= yx = x || 的官方"扩展y 在 1.9 之前的解释器版本中要么不准确要么有问题.无论如何,所指出的边缘情况似乎已经被平滑了.上面的资源声称 x ||x = yx 或 x = y 是更准确".然而,这两个都不正确,因为当 x 是以前未声明的全局变量时,它们不起作用:

The resource I mentioned above seems to suggest that the "official" expansion of x ||= y to x = x || y was either inaccurate or buggy in interpreter versions prior to 1.9. In any case, the edge case indicated seems to have been smoothed out. The resource above claims that x || x = y or x or x = y are "more accurate". Neither of those, however, is correct, because they don't work when x is a previously undeclared global variable:

[11:04:18][****@asha:~]$ irb
1.9.3-p194 :001 > a || a = 3
    NameError: undefined local variable or method `a' for main:Object
1.9.3-p194 :002 > b or b = 3
    NameError: undefined local variable or method `b' for main:Object
1.9.3-p194 :003 > c = c || 3
    => 3 

所以在 1.9.3 中,至少 x = x ||y 扩展似乎是正确的,就这些例子而言.然而,重申我的原点,我真的希望看到一些真正权威的来源解决这个问题,好吧,权威而不是像我(和其他人)所做的那样.

So in 1.9.3, at least, the x = x || y expansion appears to be correct, as far as these examples are concerned. However, to reiterate my original point, I would really like to see some truly authoritative source resolve this question, well, authoritatively rather than anecdotally as I (and others) have done.

推荐答案

这篇文章是关于规范的,阅读评论以获得不太理想的实现故事"

Ruby 草案规范 (PDF) 部分 11.4.2.3.2 相当具体地定义它(即使相当难以解释);让我们用 c ||= 3 做一个(理论上有点松散的)例子;

The Ruby draft spec (PDF) section 11.4.2.3.2 defines it fairly specifically (even if fairly hard to interpret); let's do a (theoretically somewhat loose) example with c ||= 3;

a) 评估变量作为变量引用(见 11.5.4).令 V 为结果值.

V 设置为 c

b) 评估运算符表达式或不带括号的方法调用.令 W 为结果值.

W 设置为 3.

c) 让 OP 为赋值运算符的赋值运算符名称.

OP 设置为 ||

d) 令 X 为 V OP W 形式的运算符表达式.

X 设置为 c ||3.

e) 让 I 成为 abbreviated-variable-assignment-expression 或 abbreviated-variable-assignment-statement 的变量.

I 设置为引用 c.

f) 计算变量为 I 且运算符表达式为 X 的单变量赋值表达式(参见 11.4.2.2.2).

c = c ||3 被评估.

g) 缩写变量赋值的值是评估的结果值.

赋值的结果是3.

换句话说,扩展c = c ||3 正确(不包括 1.9 之前的错误).

In other words, the expansion c = c || 3 is (excluding bugs like in pre-1.9) correct.

这篇关于||= 条件赋值运算符的官方扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆