在 Ruby 中创建凯撒密码,出现错误

Creating A Caesar Cipher in Ruby, getting an error

我正尝试在 Ruby 中为我的计算机科学 class 创建凯撒密码。我的朋友能够创建部分代码:

def cipher(word, n)
new_word = ""
word.each_char do |i|
    n.times do
        if(i == "z")
            i = "a"
            next
        elsif(i == "Z")
            i = "A"
            next
        end
        i.next!
        i == "%" ? i = " " : ""
    end
    new_word += i   
end
puts new_word
end
cipher("phrase", 5)

最后一行是您要加扰的短语的位置,数字是您要加扰的程度。其中一项要求是我们使用 gets.chomp 来指定要加扰的短语和数量,而无需编辑 .rb 文件本身。所以我想到了这个:

puts "What would you like to scramble?"
word = gets.chomp
puts "How much would you like to scramble that?"
n = gets.chomp
def cipher(word, n)
new_word = ""
word.each_char do |i|
    n.times do
        if(i == "z")
            i = "a"
            next
        elsif(i == "Z")
            i = "A"
            next
        end
        i.next!
        i == "%" ? i = " " : ""
    end
    new_word += i   
end
puts new_word
end
cipher(word, n)

并且在终端中 运行 时输出以下错误:

some.rb:10:in `block in cipher': undefined method `times' for "5":String (NoMethodError)
from some.rb:9:in `each_char'
from some.rb:9:in `cipher'
from some.rb:26:in `<main>'

如果有人能帮我找出我做错了什么,那将对我有很大帮助。

n 上致电 .to_i

您需要先将从用户输入中获得的字符串转换为数字,然后才能 运行 .times.to_i 为您完成。

示例: http://progzoo.net/wiki/Ruby:Convert_a_String_to_a_Number

前段时间做过,要求只有小写 ASCII 字母,希望你能按自己的方式做:

def encrypt(msg, key)
    msg.downcase.split("").each_with_index do |char, i|
        next if msg[i] == " "
        msg[i] = (msg[i].ord + key) > 122 ? (((msg[i].ord + key) % 123) + 97).chr : (msg[i].ord + key).chr
    end
    msg
end

def decrypt(msg, key)
    msg.downcase.split("").each_with_index do |char, i|
        next if msg[i] == " "
        msg[i] = (msg[i].ord - key) < 97  ? (123 - (97 - (msg[i].ord - key))).chr : (msg[i].ord - key).chr
    end
    msg
end

gets.chomp returns 一个字符串

word = gets.chomp

所以 word 是一个字符串,正如预期的那样,但是随后您再次调用 gets.chomp,这次是为了获取应该应用于该字符串的拼字游戏的数量。所以 n 也是一个字符串。

n = gets.chomp

当您在 n 上调用 times 方法时,它没有定义,因为它只对整数有意义。解决方案是将 n 转换为整数。这应该有效:

n = gets.chomp.to_i

更新

关于 String 实例的 to_i 方法的文档:http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i

gets.chomp return 一个字符串,必须将其转换为数字才能调用.times方法。将此行 n = gets.chomp 更改为 n = gets.chomp.to_i