【发布时间】:2015-01-29 20:39:55
【问题描述】:
这是问题:使用 Ruby 语言,让函数 CaesarCipher(str,num) 获取 str 参数并使用 num 参数作为移位数对其执行 Caesar Cipher 移位。凯撒密码的工作原理是将字符串 N 中的每个字母在字母表中向下移动(在这种情况下,N 将是 num)。标点、空格和大小写应保持不变。例如,如果字符串为“Caesar Cipher”且 num 为 2,则输出应为“Ecguct Ekrjgt”
这是我的代码
def CaesarCipher(str,num)
alphabet = ("a".."z").to_a.join("")
alphabetupcase = ("a".."z").to_a.join("").upcase
i=0
result = ""
while i < str.length
if alphabet.include?(str[i])
result += alphabet[alphabet.index(str[i]) + num]
elsif alphabetupcase.include?(str[i])
result += alphabetupcase[alphabetupcase.index(str[i]) + num]
else
result += str[i]
end
i += 1
end
# code goes here
return result
end
我不断收到此错误 (eval):11: (eval):11:in +': can't convert Fixnum into String (TypeError) from (eval):11:inCaesarCipher' from (eval):26
这有什么问题,如何修复此代码? 记住我是 Ruby 的初学者,你能提出一个更好的解决方案吗? 先谢谢大家了
【问题讨论】:
-
你在测试什么字符串?
n = CaesarCipher("hello", 1)对我来说效果很好。你使用的是什么版本的 ruby? -
老实说,我没有使用任何版本,只是在 CoderByte 的编码空间中为这个挑战做它coderbyte.com/CodingArea/information.php?ct=Caesar%20Cipher 我还在 Repl.it 上对其进行了测试,它工作了几次然后开始给出同样的错误.我不知道为什么。就像你说的,这可能是因为 Ruby 版本。