Skip to content

Instantly share code, notes, and snippets.

@josephsiefers
Last active September 24, 2015 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephsiefers/43a28b0e2522d42bb267 to your computer and use it in GitHub Desktop.
Save josephsiefers/43a28b0e2522d42bb267 to your computer and use it in GitHub Desktop.
Reverse Each Word
#step-by-step function, feel free to follow along in IRB
def reverse_each_word(sentence)
reverse_each_word = sentence.split(' ')
#collect is also known as map in some other languages, basically it takes a set A and transforms it into a set B
reversed_words = reverse_each_word.collect { |word| word.reverse }
#join does the logical OPPOSITE of split, it takes an array and creates a string according to a split character
reversed_words.join(' ')
end
#even more succinctly, leveraging the power of Ruby idioms and syntatic sugar, the whole function in can be written in ONE LINE
def reverse_each_word(sentence)
#this is one of the many reasons I LOVE Ruby...expressing something equivalent in Java is so tedious and verbose...
#however, a bit difficult to read when you're leaning Ruby because you have to understand each of these functions and their side effects
sentence.split(' ').collect(&:reverse).join(' ')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment