Ruby x,y = gets.split.map &:to_i [英] Ruby x,y = gets.split.map &:to_i
问题描述
我对这行 ruby 代码感到困惑.为什么赋值给 x、y 而不是单个变量?
I am confused about this line of ruby code. Why is the assignment given to x, y and not a single variable?
x,y = gets.split.map &:to_i
推荐答案
相反,这将数组中的第一个条目分配给 x
,将第二个条目分配给 y
分配给单个变量,在这种情况下,数组将分配给该变量.
This assigns the first entry from the array to x
, and the second entry to y
in contrast to assigning to a single variable in which case the array would be assigned to that variable.
将多个变量放在赋值的左侧是一种将数组解包为单独变量的方法.你可以在 irb 中试试这个:
Putting multiple variables on the left hand side of an assignment is a way of unpacking an array into separate variables. You can try this in irb:
irb(main):001:0> numbers = [1, 2, 3]
=> [1, 2, 3]
irb(main):002:0> first, second = numbers
=> [1, 2, 3]
irb(main):003:0> first
=> 1
irb(main):004:0> second
=> 2
查看我写的这个对旧问题的回答它提供了更多详细信息,并且是一个很好的例子,说明了它的用处.
Check out this answer to an older question that I wrote which gives some more details and is a good example of where this can be useful.
这篇关于Ruby x,y = gets.split.map &:to_i的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!