我接受了一个代码挑战,即使用以下密码信息获取用户输入并转换该输入:
replace = {
"A" => "Z",
"B" => "Y",
"C" => "X",
"D" => "W",
"E" => "V",
"F" => "U",
"G" => "T",
"H" => "S",
"I" => "R",
"J" => "Q",
"K" => "P",
"L" => "O",
"M" => "N",
"N" => "M",
"O" => "L",
"P" => "K",
"Q" => "K",
"R" => "I",
"S" => "H",
"T" => "G",
"U" => "F",
"V" => "E",
"W" => "D",
"X" => "C",
"Y" => "B",
"Z" => "A"
}
这是我的代码:
puts "Time to decipher some code: "
input = gets.chomp.upcase
replace.each do |k, v|
input.gsub!(k,v)
end
puts input
在我的each
区块中,我的密码似乎没有正确转换。任何人都可以解释为什么会这样吗?
答案 0 :(得分:1)
您正在遍历哈希replace
而不是input
字符串。那么,如果你的input = "HELLO"
......
Input: HELLO
Input: HVLLO
Input: SVLLO
Input: SVOOO
Input: SVLLL #changing back O to L
Input: HVLLL #changing back S to H
Input: HELLL #changing back V to E
由于您正在重复replace
,因此您最终会多次切换字母。
我对此问题的解决办法是迭代input
中的每个字母,然后根据replace
替换它们。为了遍历input
,我必须将其拆分,然后最终将其加入到字符串中。
答案 1 :(得分:1)
您的问题不是特定于Ruby的。这是一个非常非常非常基本(学校)级别的算法错误。你得到了你的结果,因为被替换的角色可以在以后匹配,用其他东西替换。
当人们有变量a = "foo"
和b = "bar"
并且正在尝试切换他们的值时,它会让人联想到错误:
b = a
a = b
正确执行此操作的典型方法是:
input.gsub!(/./, Hash.new{|_, k| k}.merge(replace))
答案 2 :(得分:1)
input = gets.chomp.upcase
p input.gsub(/[A-Z]/, replace)
神秘的/[A-Z]/
部分是一个正则表达式,它在字符串中搜索任何大写字符。然后gsub
将其替换为replace
哈希中的内容。
答案 3 :(得分:0)
尝试这样的事情:
replace = {
"A" => "Z",
"B" => "Y",
"C" => "X",
"D" => "W",
"E" => "V",
"F" => "U",
"G" => "T",
"H" => "S",
"I" => "R",
"J" => "Q",
"K" => "P",
"L" => "O",
"M" => "N",
"N" => "M",
"O" => "L",
"P" => "K",
"Q" => "K",
"R" => "I",
"S" => "H",
"T" => "G",
"U" => "F",
"V" => "E",
"W" => "D",
"X" => "C",
"Y" => "B",
"Z" => "A"
}
puts "Time to decipher some code: "
input = gets.chomp.upcase
output = ""
input.each_char do |c|
output << replace[c]
end
puts output
答案 4 :(得分:0)
感谢大家的帮助!我能够使用你的很多帖子来解决它,但拉曼似乎是最简单的。
replace = {
"A" => "Z",
"B" => "Y",
"C" => "X",
"D" => "W",
"E" => "V",
"F" => "U",
"G" => "T",
"H" => "S",
"I" => "R",
"J" => "Q",
"K" => "P",
"L" => "O",
"M" => "N",
"N" => "M",
"O" => "L",
"P" => "K",
"Q" => "K",
"R" => "I",
"S" => "H",
"T" => "G",
"U" => "F",
"V" => "E",
"W" => "D",
"X" => "C",
"Y" => "B",
"Z" => "A"
}
puts "Time to decipher some code: "
input = gets.chomp.upcase
output = ""
input.each_char do |c|
output << replace[c]
end
puts output