我用 Ruby 编写了一个凯撒密码加密程序。当我传入包含小写字符的字符串时,它似乎工作正常,直到我传入包含大写字符的字符串。每当我传入包含大写字符的字符串时,代码就会在行间引发 NoMethodError main.rb:7:in block in `caeser_cipher': undefined method `+' for nil (NoMethodError)
。
这是我的代码:
def caeser_cipher(string, key)
alphabet = ('a'..'z').to_a
cipher = ""
string.each_char do |char|
if alphabet.include?(char.downcase)
new_key = (alphabet.index(char) + key) % 26
char = alphabet[new_key]
end
cipher << char
end
cipher
end
puts "Enter whatever you please (of course a string of text) that you want encrypted!!!"
text = gets.chomp
puts "And then the offset value"
num = gets.chomp.to_i
puts caeser_cipher(text, num)
我尝试包装char = alphabet[new_key]
另一个 if 条件来检查char == char.upcase
,如果结果为真,则执行此操作,char = alphabet[new_key].upcase
但也失败了。