我正在尝试用 Ruby 为我的计算机科学类(class)创建凯撒密码。我的 friend 能够创建部分代码:
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>'
如果有人能帮我找出我做错了什么,那将对我有很大帮助。
最佳答案
gets.chomp 返回一个字符串
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
关于ruby - 在 Ruby 中创建凯撒密码,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003429/