ruby和python一样可以一次给多个变量同时赋值,比如a,b=1,2,表示a和b分别赋值1和2,再如:s1,s2=’75271.com’,’haotu.net’。
# 同时给三个变量赋值 a, b, c = 8, 10, 15 print "A: a = ", a, ", b = ", b, ", c = ", c, "\n"
输出
A: a = 8, b = 10, c = 15 # 交换两个变量的值 a, b = b, a print "C: a = ", a, ", b = ", b, ", c = ", c, "\n"
输出
C: a = 10, b = 8, c = 15 # 左右不对称赋值,c将得到nil a, b, c = 2, 3 print "D: a = ", a, ", b = ", b, ", c = ", c, "\n"
输出结果:
D: a = 2, b = 3, c = # 左右不对称赋值,右边多余的将不管 a, b, c = 11, 12, 13, 14, 15 print "E: a = ", a, ", b = ", b, ", c = ", c, "\n"
输出结果如下:
E: a = 11, b = 12, c = 13 # 赋值表达式右边可以是一个数组 fred = [ 4, 5, 6, 7] a, b, c = fred print "F: a = ", a, ", b = ", b, ", c = ", c, "\n"
输出结果如下:
F: a = 4, b = 5, c = 6