Created
June 12, 2013 04:04
-
-
Save georgebonnr/5762765 to your computer and use it in GitHub Desktop.
Learning exercise - original exercise was to build a program that would reverse the word order of a string. I extended it by preserving the location of the punctuation (minus apostrophes) in the sentences to make the reversed strings a little more readable / interesting. First attempt - a little sloppy, but it works!
This file contains 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
puts "Please enter a sentence." | |
user_input = gets.chomp | |
array = user_input.downcase.split(' ') | |
punct_indices = {} | |
array.each do |x| | |
contains_punct = /[[:punct:]&&[^']]/ =~ x | |
if contains_punct | |
punct_indices[array.index(x)] = x[contains_punct] | |
y = x.sub(/[[:punct:]]/, '') | |
array[array.index(x)] = y | |
end | |
end | |
reversed = array.reverse | |
if !punct_indices.empty? | |
punct_indices.each {|key, value| reversed[key] << value } | |
end | |
reversed[0].capitalize! | |
print reversed.join(' ') | |
puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Almost each action that you have separated by spaces could be a method. Then the action sequence written out, to perform what you need to have done.
Of course, that prompt routine, should probably be a routine already, and stored in a file, to be used many times.