【发布时间】:2020-07-01 21:27:34
【问题描述】:
我正在为 The Odin Project 的 Ruby 编程课程创建一个凯撒密码,我的代码达到了我有一种方法可以采用单个单词和移位值并使用相应的哈希键和值返回加密单词的程度.我还有另一种方法,它接受一个句子并将其拆分为一个包含每个分隔词的数组。我想做的是结合这两种方法,这样当你输入一个句子时,单词被分成一个数组,然后使用移位值对数组的每个部分进行加密,然后打印数组中的加密单词回到句子形式。
到目前为止,这是我的代码:
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
"e" => 5,
"f" => 6,
"g" => 7,
"h" => 8,
"i" => 9,
"j" => 10,
"k" => 11,
"l" => 12,
"m" => 13,
"n" => 14,
"o" => 15,
"p" => 16,
"q" => 17,
"r" => 18,
"s" => 19,
"t" => 20,
"u" => 21,
"v" => 22,
"w" => 23,
"x" => 24,
"y" => 25,
"z" => 26,
}```
```#multi letter caesar_cipher
def word_cipher(word, shift)
word.split(//).each {|letter| print @cipher.key(@cipher[letter]+ shift)}
end
> word_cipher("kittens", 2)
=> mkvvgpu
#split sentence string into an array of words
def sentence_array(sentence)
sentence.split.each { |word| print word.split }
end
>sentence_array("Look at all of these kittens")
=>["Look"]["at"]["all"]["of"]["these"]["kittens"]
到目前为止,我的解决方案是什么
def caesar_cipher(input, shift)
sentence_array(input) = words
words.split(//).each {|letter| print @cipher.key(@cipher[letter]+ shift)}
end
caesar_cipher("I love kittens", 2)
这是我第一次在这里发帖,如果我在解释任何事情上做得不好,我很抱歉,但任何帮助都将不胜感激!
谢谢!
【问题讨论】:
-
我弄错了上面的哈希名称是@cipher
标签: ruby methods caesar-cipher