这是我的代码:
def caesar(string, shift_factor)
alphabet = Array("a".."z")
new_alph = alphabet.rotate(shift_factor)
new_str = []
new_str = string.downcase.split("")
new_str.each do |i|
print i
if !alphabet.include?(i)
new_str.push(i)
else
equals = alphabet.index(i)
new_str.push(new_alph[equals])
end
end
end
caesar("What a string!", 0)
print new_str.join.capitalize!
代码只是继续循环,我不知道如何停止它。
答案 0 :(得分:1)
你正在迭代new_str
并且在每次迭代中你将另一个对象推到数组上,所以循环永远不会结束。
在你的循环中,如果你改为在索引处替换字符,那么你应该得到你正在寻找的结果。
def caesar(string, shift_factor)
alphabet = Array("a".."z")
new_alph = alphabet.rotate(shift_factor)
new_str = string.downcase.split("")
new_str.each_with_index do |letter, i|
if !alphabet.include?(letter)
new_str[i] = letter
else
equals = alphabet.index(letter)
new_str[i] = new_alph[equals]
end
end
end
答案 1 :(得分:1)
您需要一个不同的变量来存储结果字符串。怎么样:
def caesar(string, shift_factor)
alphabet = Array("a".."z")
new_alph = alphabet.rotate(shift_factor)
new_str = string.downcase.split("")
caesar_string = []
new_str.each do |i|
if !alphabet.include?(i)
caesar_string.push(i)
else
equals = alphabet.index(i)
caesar_string.push(new_alph[equals])
end
end
caesar_string
end
caesar_string = caesar("What a string!", 0)
print caesar_string.join.capitalize!
答案 2 :(得分:0)
只是添加一个示例,在Ruby中总是有不止一种方法:
def caesar(string, shift_factor)
alphabet = ('a'..'z').to_a
string.downcase.tr(alphabet.join, alphabet.rotate(shift_factor).join)
end