Ruby arrays place the first, second in variables, and the rest in another variable

I want to split an array into three variables; the first value in one variable, the second in another variable, and all the rest in one line, 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?

+8
variables arrays ruby
source share
3 answers

It looks as good as everyone:

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

If you do not need to save arr , you can do:

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

Others point to 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 

Like this:

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

However, this is an option to be aware of.

+9
source share

Here is an alternative form that uses splat (aka destructuring) assignment :

 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:

  • What does this mean in Ruby?
  • Where is it legal to use the ruby ​​splat operator?
+5
source share

Use the splat operator:

 arr = ["a1","b2","c3","d4","e5","f6"] var1, var2, *var3 = arr # var1 => "a1" # var2 => "a2" # var3 => ["c3", "d4", "e5", "f6"] 
+4
source share

All Articles