Ruby变量赋值

时间:2015-07-02 10:51:54

标签: ruby variable-assignment

有人可以解释这种行为:

a = b = c = 1, 2, 3 
a # => [1, 2, 3]
b # => 1
c # => 1

在作业a = b = c = 1, 2, 3中,变量abc应分配[1, 2, 3]。有什么想法吗?

3 个答案:

答案 0 :(得分:5)

  

有人可以解释为什么会发生这种情况

@shivam already answered这个问题,但添加一些括号可能会更清楚地澄清事情。

a = b = c = 1, 2, 3

被解释为:

a = [(b = (c = 1)), 2, 3]

表达式按以下顺序计算:

           c = 1
      b = (     )
a = [(           ), 2, 3]
  

应为变量abc分配[1, 2, 3]

要获得预期结果,您可以写:

a = b = c = [1, 2, 3]

被解释为:

a = (b = (c = [1, 2, 3]))

并按此顺序进行评估:

          c = [1, 2, 3]
     b = (             )
a = (                   )

答案 1 :(得分:4)

你感到困惑

a=b=c=1,2,3

实际上是:

a = (b = c = 1), 2, 3

离开

c = 1 # => 1 
b = c # => 1 
a = 1,2,3 # => [1, 2, 3] 

答案 2 :(得分:-2)

要做你正在谈论的事情你应该做如下:

a,b,c = 1,2,3
    p a #=> 1
    p b #=> 2
    p c #=> 3