【问题标题】:Issue with Ruby decryption methodRuby解密方法的问题
【发布时间】:2017-08-11 23:47:27
【问题描述】:

我试图弄清楚为什么我的 Ruby 解密方法似乎只对字母表中的某些字母无效。

该方法的目标是获取输入字符串(“new_str”)并通过用字母表中的前身重写字符串中的每个字母来解密它。即“bcd”应该返回“abc”......

我可能是错的,但它似乎适用于字母 a-j,但随后会中断字母 k-z...对于最后一组它似乎返回“a”“b”或“z”,无论信: 例如解密(“klmnopqrstuvwxyz”) 返回:“azazazazbzbzbz”

一个观察结果是,在定义的字母变量字符串中,索引号变成从字母 k(索引 10)开始的两位数......所以也许这会在公式中抛出一些东西?无论如何,任何帮助/建议表示赞赏!

def decrypt(new_str)
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  index = 0
  while index < new_str.length
    new_str[index] = alphabet.index(new_str[index])
    new_str[index] = alphabet[new_str[index] - 1]
    index +=1
  end
  puts new_str
end        

【问题讨论】:

    标签: ruby encryption methods indexing


    【解决方案1】:

    你的代码应该是这样的:

    def decrypt(new_str)
      alphabet = 'abcdefghijklmnopqrstuvwxyz'
      index = 0
      while index < new_str.length
        letter_index = alphabet.index(new_str[index])
        new_str[index] = alphabet[letter_index - 1]
        index += 1
      end
      puts new_str
    end
    
    decrypt('klmnopqrstuvwxyz') #=> jklmnopqrstuvwxy
    decrypt('abcdefghij')       #=> zabcdefghi
    decrypt('noah')             #=> mnzg
    

    在您的代码中,您通过在第 5 行执行 new_str[index] = alphabet.index(new_str[index]) 将字母转换为整数。

    PS.:这是您正在实现的 Caesar Cypher 代码。如果您对更多的 Ruby 方式来实现它感兴趣,请查看link here。

    【讨论】:

      【解决方案2】:

      使用tr 可以轻松完成替换密码。

      def decrypt(str)
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        replacement = alphabet.split('').rotate(-1).join
        str.tr(alphabet,replacement)
      end
      
      decrypt('klmnopqrstuvwxyz') #=> jklmnopqrstuvwxy
      decrypt('abcdefghij')       #=> zabcdefghi
      decrypt('noah')             #=> mnzg
      

      【讨论】:

        猜你喜欢
        • 2020-09-28
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多