Skip to content

Instantly share code, notes, and snippets.

@dannysmith
Created November 14, 2018 01:29
Show Gist options
  • Select an option

  • Save dannysmith/414010c98f5f7948c2b6e62f2ae79e62 to your computer and use it in GitHub Desktop.

Select an option

Save dannysmith/414010c98f5f7948c2b6e62f2ae79e62 to your computer and use it in GitHub Desktop.
def reverse_alternate(string)
# 1. Break the string down into an array of words.
words = string.split(' ')
# 2. Loop over each word in the array.
words.each_with_index do |word, index|
# - if the index is odd, change the word so it is reversed.
# - if the index is even, leave it as it is.
word.reverse! if index.odd?
end
# 3. Join all the words in the array together so they are a string again, with spaces between them.
# 4. Return the new string we made.
return words.join(' ')
end
reverse_alternate('one two three four') #=> 'one owt three ruof'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment