0

Is there a difference between:

1.

> lines, codelines, total_lines, total_codelines = 0, 0, 0, 0
=> [0, 0, 0, 0]

2.

> lines, codelines, total_lines, total_codelines = 0
=> 0

If yes, then which of them should be used in what situations?

[edit] there is also a third way:

    lines = codelines = total_lines = total_codelines = 0

> lines = codelines = total_lines = total_codelines = 0
=> 0
irb(main):016:0> lines
=> 0
irb(main):017:0> codelines
=> 0
irb(main):018:0> total_lines
=> 0
irb(main):019:0> total_codelines

In case of arrays

0> a = b = { }; a[:a] = 6
=> 6
irb(main):023:0> b = 3
=> 3
irb(main):024:0> a
=> {:a=>6}
irb(main):025:0> a = 10
=> 10
irb(main):026:0> b
=> 3
> a.object_id
=> 21
irb(main):028:0> b.object_id
=> 7
4

2 回答 2

2

The difference between those two is that the second example is only assigning 0 to lines.

lines, codelines, total_lines, total_codelines = 0,0,0,0

codelines #=> 0

Whereas when the amount of rvalues in the parallel assignment is smaller than the amount of lvalues:

lines, codelines, total_lines, total_codelines = 0

codelines #=> nil

The surplus values are assigned with nil

So, the second type of parallel assignment does not really make sense unless you need to initialize a variable with nil in a particular scope; for example a counter outside an iteration.

于 2013-05-06T07:18:38.267 回答
1

它们是有区别的。

1.

lines, codelines, total_lines, total_codelines = 0, 0, 0, 0

右侧的值与左侧的变量一样多。每个值都将分配给每个变量。

2.

lines, codelines, total_lines, total_codelines = 0

右侧的值没有左侧的变量多。缺失值将被补充为nillines会变成0,剩下的都会变成nil。你没有理由像这样使用赋值。

当您想要使用右侧值数量较少的多个变量时,一个典型的情况是当您有一个不知道它有多少元素的数组时。

a, b, *c = some_array

在上述情况下,根据 , , , 的长度,将some_array分配不同的东西。abc

于 2013-05-06T07:22:25.737 回答