我编写了一个代码,用于使用简单的替换密码(a=b、b=c 等)将纯文本消息转换为密文消息。空格被替换为“1”。
然后我想这样做,以便我可以使用“gets”输入不同的消息。这导致了一个问题,我通过用“gets.strip”替换“gets”解决了这个问题。如果 get 是在输入的字符串中添加一个空格,无论是在开头还是结尾,为什么会导致问题?我有一种处理空格的方法,所以它真的是“”还是零空格(因为没有更好的词)或字符返回或什么?这是我写的:
base_alph =[" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
code_alph = ["1", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"]
x=0
base_msgarray = []
code_msgarray = []
puts "type what you want to translate below"
base_msg = gets.strip # without the .strip the program doesn't run
msg_size = base_msg.length
puts "the message is translated as:"
loop do #this section populates an array with all the characters from the gets
break if x >= msg_size
base_msgarray.push(base_msg[x])
x += 1
end
# this section passes in the values of the base_msgarray to |letter| to then determine its key
# in base_alph then that key is passed into code_alph to find the translated letter which
# is then used to populate the code_msgarray
base_msgarray.each do |letter|
code_index = base_alph.index(letter)
code_msgarray.push(code_alph[code_index])
end
# this section displays the values of code_msgarray in a more text-like fashion
code_msgarray.each do |codeletter|
print codeletter
end
gets # for some reason if i dont have this here the terminal window disappears before I can read anything