Skip to content

Instantly share code, notes, and snippets.

@georgebonnr
Created June 12, 2013 04:04
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 georgebonnr/5762765 to your computer and use it in GitHub Desktop.
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!
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
@kotp
Copy link

kotp commented Jun 12, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment