Search code examples
rubywhile-loopuser-input

Reading word into an array [ruby]


Trying to create a ceaser cipher in Ruby. The problem I'm facing is that when the program reaches the while loop, it only performs the desired operation on the very last letter of the inputted word. Before I delve further into what I've tried, please find the code:

#!/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

I'm thinking that the problem lies with the logic for the while loop. The way I am going to attack this is by reading the pre-converted word into an array, as opposed to using the .each_byte object.

I don't know how to do that and the guides/questions I've found don't quite answer the question. If anyone knows how to do this, or knows a better way of solving this- I'd be much appreciative.


Solution

  • you don't need the last while loop

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