简体   繁体   中英

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 = ["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:

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) :

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM