Last active
September 24, 2015 02:02
-
-
Save josephsiefers/43a28b0e2522d42bb267 to your computer and use it in GitHub Desktop.
Reverse Each Word
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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