我想将一个数组拆分为三个变量;将第一个值转换为一个变量,将第二个值转换为另一个变量,将所有其余值转换为一个字符串,例如:
arr = ["a1","b2","c3","d4","e5","f6"] var1 = arr[0] # var1 => "a1" var2 = arr[1] # var2 => "b2" var3 = ? # var3 should be => "c3d4e5f6"
为每个变量实现列出的值需要什么代码?
解决方法
这似乎和任何东西一样好:
arr = ["a1","f6"] var1 = arr[0] # => "a1" var2 = arr[1] # => "b2" var3 = arr[2..-1].join # => "c3d4e5f6"
如果你不需要保存arr,你可以这样做:
arr = ["a1","f6"] var1 = arr.shift # => "a1" var2 = arr.shift # => "b2" var3 = arr.join # => "c3d4e5f6"
其他人指出splat运算符,这是可以理解的,但我认为这比上面更糟糕:
arr = ["a1","f6"] var1,var2,*tmp = arr var3 = tmp.join
就是这样:
arr = ["a1",*var3 = arr var3 = var3.join
不过,这是一个值得注意的选择.