That's just how array assignment works in Ruby. It's trying to be clever, a little, by assigning each indexed item of the array to that variable on the left-hand side of the assignment =
Why doesn't assigning a variable to an array yield expected results in Ruby?
-
29-05-2022 - |
質問
Using IRB, I tested the following:
C:\Pickaxe>irb
irb(main):001:0> list_of_strings = %w{ a list of strings in an array }
=> ["a", "list", "of", "strings", "in", "an", "array"]
irb(main):002:0> a, b, c = list_of_strings
=> ["a", "list", "of", "strings", "in", "an", "array"]
irb(main):003:0> a
=> "a"
irb(main):004:0> b
=> "list"
irb(main):005:0> c
=> "of"
irb(main):006:0>
In the other languages I've developed in setting a, b, c = d
sets the values of a
, b
and c
to equal d
in its entirety. Here they are set to successive elements in the array.
I don't understand how or why this works. Could someone shed light on the issue?
解決
所属していません StackOverflow