Ruby 如何从另一个方法中访问两个方法?
我正在为Odin项目的Ruby编程课程创建一个caesar密码,我的代码已经达到了这样的程度:我有一个方法可以接受一个单词和一个移位值,并使用相应的哈希键和值返回加密的单词。我还有另一种方法,它把一个句子分成一个数组,每个数组包含一个单独的单词。我想做的是将这两种方法结合起来,这样当你输入一个句子时,单词被分成一个数组,然后数组的每个部分都用移位值加密,然后数组中加密的单词被打印回句子形式 以下是我目前的代码:Ruby 如何从另一个方法中访问两个方法?,ruby,methods,caesar-cipher,Ruby,Methods,Caesar Cipher,我正在为Odin项目的Ruby编程课程创建一个caesar密码,我的代码已经达到了这样的程度:我有一个方法可以接受一个单词和一个移位值,并使用相应的哈希键和值返回加密的单词。我还有另一种方法,它把一个句子分成一个数组,每个数组包含一个单独的单词。我想做的是将这两种方法结合起来,这样当你输入一个句子时,单词被分成一个数组,然后数组的每个部分都用移位值加密,然后数组中加密的单词被打印回句子形式 以下是我目前的代码: "a" => 1, "b" =
"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)
这是我第一次在这里发帖,所以如果我在解释任何事情时做得不好,我很抱歉,但任何帮助都将不胜感激
谢谢 您必须稍微修改方法:
#multi letter caesar_cipher
def word_cipher(word, shift)
output = ''
word.split(//).each {|letter| output << @cipher.key(@cipher[letter]+ shift)}
output
end
def sentence_array(sentence)
sentence.split
end
#multi letter caesar_cipher
def caesar_cipher(input, shift)
output = ""
words = sentence_array(input)
words.each do |word|
output << word_cipher(word.downcase, shift)
output << " " unless word == words.last
end
output.capitalize
end
puts caesar_cipher("I love kittens", 2)
#多字母凯撒密码
def word_密码(word,shift)
输出=“”
split(/)。我在散列名称上方的每个{字母|输出都是@cipher