Mahesh Mesta Mahesh Mesta - 9 months ago 25
Ruby Question

How to achieve all elements swapped in an array

I have an ordered array which contain 1 to 1000000 elements.
I want to achieve an array such that the elements in the array are swapped with its next element.For instance if we assume the array elements are


I want to return an array with elements as


How do I achieve this in ruby for 100000 such elements? Can anyone guide me?

a = [1,2,3,4,5,6]
a.each_slice(2).map{|inner_a| inner_a.reverse}.flatten
# => [2, 1, 4, 3, 6, 5]


a.each_slice(2)returns an enumerator (#<Enumerator: [1, 2, 3, 4, 5, 6]:each_slice(2)>) with two element couples from your array. To see try a.each_slice(2).to_a. This returns [[1, 2], [3, 4], [5, 6]] with I only have to flatten for your expected result.

See also the first comment if you prefer a shorter notation of it.