[英]ruby arrays put first, second into variables, and the rest into another variable
I want to split an array into three variables; 我想将一个数组拆分为三个变量; the first value into one variable, the second one into another variable, and all the rest into one string, for example: 将第一个值转换为一个变量,将第二个值转换为另一个变量,将所有其余值转换为一个字符串,例如:
arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0] # var1 => "a1"
var2 = arr[1] # var2 => "b2"
var3 = ? # var3 should be => "c3d4e5f6"
What code is needed to achieve the listed values for each variable? 为每个变量实现列出的值需要什么代码?
This seems as good as anything: 这似乎和任何事情一样好:
arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0] # => "a1"
var2 = arr[1] # => "b2"
var3 = arr[2..-1].join # => "c3d4e5f6"
If you don't need to preserve arr
, you could do: 如果你不需要保留arr
,你可以这样做:
arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr.shift # => "a1"
var2 = arr.shift # => "b2"
var3 = arr.join # => "c3d4e5f6"
Others are pointing out the splat operator, which is understandable, but I think this is worse than the above: 其他人指出splat运算符,这是可以理解的,但我认为这比上面更糟糕:
arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *tmp = arr
var3 = tmp.join
As is this: 就是这样:
arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *var3 = arr
var3 = var3.join
Still, it's an option to be aware of. 不过,这是一个值得注意的选择。
Here is an alternative form that uses splat assignment (aka array destructuring) : 这是一个使用splat赋值(aka数组解构)的替代形式:
arr = ["a1","b2","c3","d4","e5","f6"]
# "splat assignment"
var1, var2, *var3 = arr
# note that var3 is an Array:
# var1 -> "a1"
# var2 -> "b2"
# var3 -> ["c3","d4","e5","f6"]
See also: 也可以看看:
Use the splat operator: 使用splat运算符:
arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *var3 = arr
# var1 => "a1"
# var2 => "a2"
# var3 => ["c3", "d4", "e5", "f6"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.