Ruby, how to swap the elements in an array?

How do I swap an(example) array's second and third elements? I tried the following

def swap_elements(array)
array = ["blake", "ashley", "scott"]
    array[1], array[2] = array[2], array[1]

but I get

: ["scott", "ashley"]

I lost the first[0] element

1 answer

  • answered 2022-05-04 03:38 max

    There are many ways to do this - this is a functional approach that doesn't mutate the original array:

    def swap_elements(array)
      # yields the array to the block
      array.then do |first, *rest| # deconstruct the array  
        rest.reverse # swap the places of 2 & 3
            .unshift(first) # put the first back in

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum