The Problem: Given a string, write a function to return the string reversed.
In-place algorithms, sometimes called destructive algorithms, work by modifying the input data structures themselves.
Said another way, when given a string, and in-place algorithm will permanently change that string.
On one hand,
slice creates a shallow copy of a portion of an array without changing the original array.
splice permanently changes the original array by removing and/or adding values to it, and therefore operates in-place.
Given a string, how would we approach creating a function that will reverse the string in-place?
Typically, in-place algorithms will require swapping elements.
We can work through the string letter by letter by splitting it into an array, swapping the first letter with the last letter, the second with the second last, and so one.
To do this we will use indices to track our progress until they meet in the centre.
Computationally this will only be on the order of O(n) time.
Paste in our function above and test it by passing various strings to see the output.
We can run interactive ruby from the command line by entering
irb, just like how we did with
Paste in the above function and test by passing in various strings to see the input reversed.
Modifying data in-place is useful.
Just keep in mind that you are permanently altering the data received by the function. 😉