How do I move an element of an array one place up/down with Ruby

  • A+

Let's say I have this array

array = ['a', 'b', 'c', 'd'] 

What is a good way to target an element (for example 'b') and switch it with the next element in line (in this case 'c') so the outcome becomes:

=> ['a', 'c', 'b', 'd'] 

array[1], array[2] = array[2], array[1] array #=> ["a", "c", "b", "d"] 


array[1, 2] = array.values_at(2, 1) array #=> ["a", "c", "b", "d"] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: