gpt4 book ai didi

ruby - 名为 noMethodError ruby​​ 的私有(private)方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:20 24 4
gpt4 key购买 nike

我一直在尝试解决以下问题,但遇到了错误。问题的重点是使用给定的 key 序列来加密字符串。例如,当给定“cat”和 [1,2,3] 时,结果应为“dcw”有什么建议么?错误如下

def vigenere_cipher(string, key_sequence)
keyIndex=0
string=string.each_char.map do |c|
c=c.shift!(c,keyIndex)
keyIndex+=1
if keyIndex=key_sequence.length
keyIndex=0
end
end
return string
end

def shift!(c,keyIndex)
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
inititalLetterIndex=alphabet.index(c)
finalLetterIndex=alphabet[inititalLetterIndex+keyIndex]
return alphabet[finalLetterIndex]
end

vigenere_cipher("cat", [1,2,3])
# private method `shift!' called for "c":String (NoMethodError)

最佳答案

您正在尝试对未在 String 类上定义的字符串对象调用 shift!,而是在主对象上定义。您可以像 shift!(c,keyIndex) 那样调用它,而不是 c.shift!(c,keyIndex)

关于ruby - 名为 noMethodError ruby​​ 的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com