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
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
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.
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.