将单词读入数组 [红宝石]



试图在 Ruby 中创建停止密码。 我面临的问题是,当程序到达 while 循环时,它只对输入单词的最后一个字母执行所需的操作。在我进一步深入研究我所尝试的内容之前,请找到代码:

#!/usr/bin/ruby

#print 65.chr  ASCII code for A
#print 97.chr  ASCII code for a
a = 0
b = 97
d = []
e = 0
# Just to print the alphabet alongside the ASCII value 
# (For sanity checking)
while a <= 25
print b.chr + " "
print b.to_s + "n"
a = a + 1
b = b + 1
end
puts "n Please enter a word to translate"
word = gets.strip
# The desired effect is to move the letter along by key value
puts "Please enter a key"
k = gets.chomp.to_i
# In its current state, what happens is only the last char
# is moved along by the key value. 
while e <= word.length
word.each_byte do |c|
d[e] = c + k
end
e = e + 1
end

puts d

我认为问题出在 while 循环的逻辑上。我要解决这个问题的方法是将预转换的单词读取到数组中,而不是使用 .each_byte 对象。

我不知道该怎么做,我找到的指南/问题并不能完全回答这个问题。如果有人知道如何做到这一点,或者知道解决这个问题的更好方法 - 我将不胜感激。

你不需要最后一个while循环

word.each_byte do |c|
d[e] = c + k
e = e + 1
end

更冗长的东西:

alphabet = ('a'..'z').to_a
new_word = ''
puts "n Please enter a word to translate"
word = gets.strip
puts "Please enter a key"
k = gets.chomp.to_i
word.split('').each_with_index do |letter, index|
alphabet_index = alphabet.index(letter)
new_index = alphabet_index + key
new_word[index] = alphabet[new_index]
end
puts "Your translated word is #{new_word}"

凯撒密码是一个简单的移位密码

word.each_byte do |c| 
p c + k 
end

设法让它工作,感谢所有的帮助...任何感兴趣的人的代码:

#!/usr/bin/ruby
#print 65.chr  A
#print 97.chr  a
a = 0
b = 65
y = 97
d = []
e = 0
while a <= 25
print y.chr + " = " + y.to_s + " "
print b.chr + " = " + b.to_s + " " + "n"
a = a + 1
b =  b + 1
y = y + 1
end

puts "n Please enter a word to translate"
word = gets.strip
puts "Please enter a key"
k = gets.chomp.to_i
word.each_byte do |c|
d[e] = c + k
e = e + 1
end
print "n"
a = 0
arlen = d.count

while a != arlen
print d[a].chr
a = a + 1
end
print k

最新更新