Last active
August 29, 2015 13:57
-
-
Save RoelCastano/9691268 to your computer and use it in GitHub Desktop.
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
# ----------------------------------------------------- # | |
# Roel Castaño Moreno. # | |
# March 21, 2014. # | |
# Problem 2 for Icalia Labs. # | |
# ----------------------------------------------------- # | |
# Function that reverses the string "str" | |
def reverse_words(str) | |
# Variable that stores location of space | |
sp = str.index(" ") | |
# Variable that stores start of the next word to reverse | |
st = 0 | |
# Iterates through the spaces in the sentence while it finds spaces | |
while (sp != nil) | |
# Stored location of the center of the sentence | |
middle = (sp-st) / 2 | |
# Iterates through word inverting the letters | |
middle.times do |i| | |
str[st], str[sp-(i+1)] = str[sp-(i+1)], str[st] | |
st = st + 1 | |
end | |
# Stored start of next word | |
st = sp + 1 | |
# Looks for the next space | |
sp = str.index(" ", sp+1) | |
end | |
# Reverses last word | |
sp = str.length | |
middle = (sp - st) / 2 | |
middle.times do |i| | |
str[st], str[sp-(i+1)] = str[sp-(i+1)], str[st] | |
st = st + 1 | |
end | |
end | |
# Asks for user's input (sentence to be processed). | |
print "Please write a sentence: " | |
sentence = gets.chomp | |
# Input sentence into function to be reversed | |
reverse_words(sentence) | |
# Print reversed sentence | |
puts sentence |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment