Skip to content

Instantly share code, notes, and snippets.

@ScottGo
Last active December 15, 2015 21:49
Show Gist options
  • Save ScottGo/5328163 to your computer and use it in GitHub Desktop.
Save ScottGo/5328163 to your computer and use it in GitHub Desktop.
Write a method reverse_words which takes a sentence as a string and reverse each word in it.
#from stackoverflow, want to see if/how it works, not taking credit or will use if it does
def reverse_words(string) # Method reverse_string with parameter 'string'.
loop = string.length # int loop is equal to the string's length.
word = '' # This is what we will use to output the reversed word.
while loop > 0 # while loop is greater than 0, subtract loop by 1 and add the string's index of loop to 'word'.
loop -= 1 # Subtract 1 from loop.
word += string[loop] # Add the index with the int loop to word.
end # End while loop.
return word # Return the reversed word.
end # End the method.
def random_word(length = 5)
rand(36**length).to_s(36)
end
describe "reverse_words" do
it "does nothing to an empty string" do
reverse_words("").should eq ""
end
it "reverses a single word" do
word = random_word
reverse_words(word).should eq word.reverse
end
it "reverses two words" do
word1 = random_word
word2 = random_word
reverse_words("#{word1} #{word2}").should eq "#{word1.reverse} #{word2.reverse}"
end
it "reverses a sentence" do
reverse_words("Ich bin ein Berliner").should eq "hcI nib nie renilreB"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment