什么是“(test1,test2,test3 =”3“,测试4 =”4“,测试5 =”5“,测试6 =”6“)”做什么?

时间:2010-06-17 20:44:03

标签: ruby

这个问题是基于我最近在同事工作中找到的一些非常奇怪的代码。他声称不知道它是如何工作的,只有他从其他地方复制它。这对我来说不够好,我想了解这里发生了什么。

如果我们有类似的话:

(test1, test2, test3="3", test4="4")

结果将是test1 == "3"test2 == "4"test3 == niltest4 == "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

3 个答案:

答案 0 :(得分:3)

它看起来像是这样执行:

(test1, test2, test3) = ("3"), (test4 = "4"), (test5 = "5"), (test6 = "6")

# Equivalent:
test1 = "3"
test2 = test4 = "4"
test3 = test5 = "5"
      ; test6 = "6"

答案 1 :(得分:2)

赋值语句返回RHS(表达式的右侧),这是a = b = 4ab设置为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"

答案 2 :(得分:1)

当我运行你的第二个例子时:

(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]