如何在 ruby 中加密字符串
下面的方法应该采用“加密”字符串并返回“未加密”字符串,但它返回错误“undefined method `-' for nil (NoMethodError)” 我已经尝试了一切,但我无法超越。 基本上代码是这样的:
ALPHABET = ('a'..'z').to_a
def decode(string, factor)
string = string.split(//)
string = string.each_with_index.map do |char, _|
if char.match(/\w/).nil?
char
else
ALPHABET[ALPHABET.index(char) - factor]
end
end
string.join
end
nil:NilClass 的未定义方法“-”
如何解决这个问题?
The method below should take an "encrypted" string and return the string "unencrypted", but it is returning the error "undefined method `-' for nil (NoMethodError)"
I've tried everything but I can't get beyond that.
basically the code is this:
ALPHABET = ('a'..'z').to_a
def decode(string, factor)
string = string.split(//)
string = string.each_with_index.map do |char, _|
if char.match(/\w/).nil?
char
else
ALPHABET[ALPHABET.index(char) - factor]
end
end
string.join
end
undefined method `-' for nil:NilClass
How can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仅使用小写字母设置
ALPHABET
(ALPHABET = ('a'..'z').to_a
),但在字符串中,您使用了一些大写字母(“Z”、“V”)。由于这些字母不会出现在 ALPHABET 上,因此与它们相关的索引不存在并且将为nil
(例如ALPHABET.index('Z')
为零
)。为了解决这个问题,考虑到输出中的字母大小写不相关,您可以对字符串进行预处理,将所有字母转换为小写,然后您将得到预期的结果:
UPDATE
在这种情况下,您可以定义两个字母表(一个用于小写,一个用于大写),然后相应地使用它们。像这样:
You are setting your
ALPHABET
only with lower case letters (ALPHABET = ('a'..'z').to_a
), but in the string, you are using some upper case letters ('Z', 'V'). As these letters won't be on the ALPHABET, the index related to them does not exist and will benil
(e.gALPHABET.index('Z')
isnil
).In order to solve that, considering that the letters case on the output is not relevant, you can just do a preprocessing on your string converting all the letters to lower case, and you will then get the expected result:
UPDATE considering that the case is relevant:
In this case, you can then define two alphabets (one for lower case and one for upper case), and then use them accordingly. Like this:
另一种只有一个字母的版本:
代码的优先级是可读性/简洁性而不是速度。
Another version with one alphabet:
Priority of the code is readability/brevity over speed.