Skip to content

Instantly share code, notes, and snippets.

@RoelCastano
Last active August 29, 2015 13:57
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 RoelCastano/9691268 to your computer and use it in GitHub Desktop.
Save RoelCastano/9691268 to your computer and use it in GitHub Desktop.
# ----------------------------------------------------- #
# 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