Ruby解密方法的问题 [英] Issue with Ruby decryption method

查看:147
本文介绍了Ruby解密方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图找出为什么我的Ruby解密方法似乎只对字母表中的某些字母打破。

I'm trying to figure out why my Ruby decryption method seems to break only for certain letters of the alphabet.

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

The goal of the method is to take an input string ("new_str") and decrypts it by rewriting EACH letter in the string with its predecessor in the alphabet. i.e. "bcd" should return "abc" ...

我可能错了,但它似乎适用于字母aj,但随后打破字母kz ..对于最后一组,无论字母如何,它似乎都会返回ab或z:
eg decrypt(klmnopqrstuvwxyz)
返回:azazazazazbzbzbz

I could be wrong but it seems to work for the letters a-j, but then breaks for the letters k-z... for that last set it seems to return either an "a" "b" or "z" no matter the letter: e.g. decrypt("klmnopqrstuvwxyz") returns: "azazazazazbzbzbz"

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

One observation is that in the defined alphabet variable string, the index numbers become double digits starting at the letter k (index 10)... so maybe that's throwing something off in the formula? Anyway, any help / suggestions appreciated!

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        


推荐答案

你的代码应该是这样的:

Your code should be like:

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

在您的代码中,您通过执行 new_str [index] = alphabet.index(new_str [index])在第5行。

In your code, you were switching a letter by an integer number by doing new_str[index] = alphabet.index(new_str[index]) in the 5th line.

PS:这是凯撒Cypher你正在实现的代码。如果您对更实用的Ruby方式感兴趣,请查看链接到这里

PS.: This is a Caesar Cypher code you are implementing. If you are interested in a more Ruby way to implement it, check this link here.

这篇关于Ruby解密方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆