Here is the assigned problem:
Using the Ruby language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.*
I figured I'd attack this in two parts, however I cannot seem to figure out what I am doing wrong with the first half of the problem!
Here is my code as it currently stands.
def LetterChanges(str)
str.downcase!
str = str.split(//)
alphabet_lower = ["a".."z"]
i = 0
letter = 0
while i < str.length - 1
if alphabet_lower[letter] == str[i]
str[i] = alphabet_lower[letter + 1]
i += 1
letter = 0 ## Added this for the instance when letter > 0 after an 'else'
else
letter += 1
end
end
str = str.join("")
return str
end
This code is having infinite loop. I did try a few other things such as
......
i = 0
alphabet.each do |letter|
if str[i] == letter
str[i] = letter.next ##I also tried letter + 1
i += 1
end
end
......
Most probably, your
if alphabet_lower[letter] == str[i]
doesn't get a match, thus yourletter
increments to infinity, and you get an infinite loop. You can verify this by adding aputs
on yourelse
. It would help if you do as Yu Hao said and place your input and it's output. Also, kindly post the calling script for yourLetterChanges
.As for the Socratic Way: The question left, is why does your
if alphabet_lower[letter] == str[i]
doesn't get a match? And how can you get around with it? :)