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?
The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.
Appending or pushing arrays, elements, or objects to an array is easy. This can be done using the << operator, which pushes elements or objects to the end of the array you want to append to. The magic of using << is that it can be chained.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With