I am using Ruby to take in a string and reverse the order of the letters (so that the last letter becomes the first, etc.)
When I use the below code, I accidentally create a palindrome by taking half of the string and repeating it:
def reverse(word)
i = 0
new_word = word
while i < word.length
new_word [i] = word [word.length - i - 1]
i += 1
end
return new_word
end
puts reverse("cat") # => "tac"
puts reverse("programming") # => "gnimmargorp"
puts reverse("bootcamp") # => "pmactoob"
However, when I use the below code, I get it right:
def reverse(word)
i = 0
new_word = ""
while i < word.length
new_word [i] = word [word.length - i - 1]
i += 1
end
return new_word
end
puts reverse("cat") # => "tac"
puts reverse("programming") # => "gnimmargorp"
puts reverse("bootcamp") # => "pmactoob"
I just changed word to "" (line 4) and it works. Why?
My suspicion is that the string (word) itself is changing with each iteration, but it isn't supposed to do that is it?
Thank you all.