ruby数组将第一个,第二个放入变量,其余放入另一个变量

时间:2013-06-05 00:47:18

标签: ruby arrays variables

我想将数组拆分为三个变量;将第一个值转换为一个变量,将第二个值转换为另一个变量,将所有其余值转换为一个字符串,例如:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0] # var1 => "a1"
var2 = arr[1] # var2 => "b2"
var3 = ? # var3 should be => "c3d4e5f6"

为了实现每个变量的列出值需要什么代码?

3 个答案:

答案 0 :(得分:16)

这似乎与任何事情一样好:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0]            # => "a1"
var2 = arr[1]            # => "b2"
var3 = arr[2..-1].join   # => "c3d4e5f6"

如果您不需要保留arr,则可以执行以下操作:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr.shift   # => "a1"
var2 = arr.shift   # => "b2"
var3 = arr.join    # => "c3d4e5f6"

其他人指出splat运算符,这是可以理解的,但我认为这比上面的更糟糕:

arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *tmp = arr
var3 = tmp.join

就是这样:

arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *var3 = arr
var3 = var3.join

不过,这是一个需要注意的选项。

答案 1 :(得分:5)

以下是使用splat assignment (aka array destructuring)的替代表单:

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"]

另见:

答案 2 :(得分:4)

使用splat运算符:

arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *var3 = arr

# var1 => "a1"
# var2 => "a2"
# var3 => ["c3", "d4", "e5", "f6"]