What is the easiest way to convert a ruby array to an array of consecutive pairs of its elements?
I mean:
x = [:a, :b, :c, :d]
Expected result:
y #=> [[:a, :b], [:c, :d]]
Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .
Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
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.
Use Enumerable#each_slice
:
y = x.each_slice(2).to_a #=> [[:a, :b], [:c, :d]] [0, 1, 2, 3, 4, 5].each_slice(2).to_a #=> [[0, 1], [2, 3], [4, 5]]
Hash[*[:a, :b, :c, :d]].to_a
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