Ruby Caesar Cipher

时间:2015-12-02 19:29:12

标签: ruby

我正在尝试在Ruby中实现一个Caesar Cipher,我不确定为什么我的代码不起作用:

l_alphabet = ("a".."z").to_a
u_alphabet = ("A".."Z").to_a
num = 5
string = "Hello world, my name is Mark!"
newstring = ""
string.each_char do |a|
    if !l_alphabet.include?(a) && !u_alphabet.include?(a)
        newstring += a
    else
        if l_alphabet.include?(a)
            newstring += l_alphabet[l_alphabet.index(a) + num]
        else
            newstring += u_alphabet[u_alphabet.index(a) + num]
        end
    end    
end

puts newstring

我收到了这4个错误,我不确定它们是什么意思。

no implicit conversion of nil into String
(repl):11:in `+'
(repl):11:in `block in initialize'
(repl):6:in `each_char'
(repl):6:in `initialize'

1 个答案:

答案 0 :(得分:3)

您正在将索引扩展到字母表的边界之外。你必须检查字母索引+ num> 26(字母表中的字母)。如果是,则索引=索引%26将位置包回到数组的前面。

l_alphabet = ("a".."z").to_a
u_alphabet = ("A".."Z").to_a
num = 5
string = "Hello world, my name is Mark!"
newstring = ""
string.each_char do |a|
    if !l_alphabet.include?(a) && !u_alphabet.include?(a)
        newstring += a
    else
        if l_alphabet.include?(a)
          index = l_alphabet.index(a) + num
          if index > 26 
            index = index % 26
          end
          newstring += l_alphabet[index]
        else
          index = u_alphabet.index(a) + num
          if index > 26
            index = index % 26
          end
            newstring += u_alphabet[index]
        end
    end    
    puts newstring
end