Ruby arrays put first, second into variables, and the rest into another variable

arraysrubyvariables

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?

Best Solution

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.