这个问题是基于我最近在同事的工作中发现的一些非常奇怪的代码。他声称不知道它是如何工作的,只是他从其他地方抄袭来的。这对我来说还不够好,我想知道这里发生了什么。
如果我们有这样的东西:
(test1, test2, test3="3", test4="4")结果将是test1 == "3"、test2 == "4"、test3 == nil和test4 == "4"。我理解为什么会发生这种情况,但如果我们这样做:
(test1, test2, test3="3", test4="4", test5 = "5", test6 = "6")现在结果是test1 == "3",test2 == "4",test3 == "5",test4 == "4",test5 == "5",test6 == "6"。
为什么test5 == nil不是
发布于 2010-06-18 04:54:04
它看起来像是这样执行的:
(test1, test2, test3) = ("3"), (test4 = "4"), (test5 = "5"), (test6 = "6")
# Equivalent:
test1 = "3"
test2 = test4 = "4"
test3 = test5 = "5"
; test6 = "6"发布于 2010-06-18 05:15:39
赋值语句返回RHS (表达式的右侧),这是a = b = 4将a和b都设置为4的方式:
a = b = 4
-> a = (b = 4) // Has the "side effect" of setting b to 4
-> a = 4 // a is now set to the result of (b = 4)记住这一点,以及Ruby允许在一条语句中进行多个赋值的事实,您的语句可以重写(Ruby看到逗号和等号,并认为您正在尝试进行多个赋值,第一个等号将LHS (左侧)和RHS分开):
test1, test2, test3="3", test4="4", test5 = "5", test6 = "6"
-> test1, test2, test3 = "3", (test4 = "4"), (test5 = "5"), (test6 = "6")RHS首先被评估,这给我们留下了:
test1, test2, test3 = "3", "4", "5", "6"副作用是将test4设置为"4",将test5设置为"5",将test6设置为"6"。
然后评估LHS,并可以重写为:
test1 = "3"
test2 = "4"
test3 = "5"
// since there are 3 items on the LHS and 4 on the RHS, nothing is assigned to "6"因此,在语句的末尾,将设置六个变量:
test1 == "3"
test2 == "4"
test3 == "5"
test4 == "4"
test5 == "5"
test6 == "6"发布于 2010-06-18 05:23:29
当我运行你的第二个例子时:
(test1, test2, test3="3", test4="4", test5 = "5", test6 = "6")我得到的结果与你报告的结果不同:
test1=="3", test2=="4", test3=="5", test4=="4", test5=="5", test6=="6"(注意,test4是"4",而不是"6")
这对我来说很有意义,因为它是这样解析的:
((test1, test2, test3) = ("3", (test4="4", (test5 = "5", (test6 = "6")))))所以你得到的评估是这样的:
((test1, test2, test3) = ("3", (test4="4", (test5 = "5", (test6 = "6")))))
[assign "6" to test6]
((test1, test2, test3) = ("3", (test4="4", (test5 = "5", "6"))))
[assign "5" to test5]
((test1, test2, test3) = ("3", (test4="4", "5", "6")))
[assign "4" to test4]
((test1, test2, test3) = ("3", "4", "5", "6"))
[assign "3", "4", and "5" to test1, test2, and test3 respectively]https://stackoverflow.com/questions/3065488
复制相似问题