First, you forgot to reset the counter N between consecutive the words. You set the N to zero, then you start to iterate over the words.
So, in the overview, your algo behaves like that:
For first word, the N iterates over 0..25
For second word, the N starts with 26, and DOES NOT iterate at all
For third word, the N starts with 26, and does not iterate
..
etc.
So, for complete starters, do:
array1 = Array.new
array1 = ('A'..'Z').to_a
array2 = Array.new
array2 = ('A'..'Z').to_a
array2 = array2.rotate(2)
puts "enter a word:"
word1 = gets.chomp
word1 = word1.upcase.split(//) # <-- note that you REPLACE the input string
# with an sequence of STRINGS produced by SPLIT
word1.each do # for each STRING in the SEQUENCE
n = 0
while n < 26 # scan all 26 letters from ARRAY
if word1[n] == array1[n] # ... WTF
word1[n] = array2[n]
end
n += 1
end
end
Now you will keep the letter scanning at least running in the same way for every one word. However, this will not work as expected either, but wholly different reason.
How do you use the N actually?
if word1[n] == array1[n]
word1[n] = array2[n]
end
So, you read Nth WORD from the SEQUENCE
.. and compare it against Nth LETTER from the array1.
Is it really what you wanted to do? Quite not.
You most probably wanted to replace every letter in WORD along with letter-pairs formed by the two arrays.
So, instead, you wanted to:
You can compact it into oneliner too:
-- loop
-- loop2
word[position] = array2[array1.index(word[position])]
However, please note that I say now position, not N. You've used N as range 0..25, which means the index of the letter in ARRAY.
But, for inspecting the word's letters, you need to iterate over the word's letters. How long is the word? Certainly, not 0..25!
Also note the subtle change: word instead of word1. I say "word" and "word's letters", not "arrayofwords". Originally, you used N also to read Nth word from the sequence, let's keep it. But as we need to iterate over word's leters, a different variable is needed, 'say position:
n = 0
arrayOfWords.each do
word = arrayOfWords[n]
position = 0
while position < word.length
letter = word[position]
letterindex = array1.index(letter)
substitution = array2[letterindex]
word[position] = subsitution
position += 1
end
n += 1
end
Note how N stays and only increases with each word, and how position is reset everytime to zero, to iterate over actual length of the current word.
In Ruby, this is overly elaborate way to do that. Ruby has a lot of nice tricks that can shorten the code. For example, the each method is not only a loop. It actually gives you each word*, you don't need the N at all:
arrayOfWords.each do |word|
position = 0
while position < word.length
word[position] = array2[array1.index(word[position])]
position += 1
end
end
Note how I added "word" in bars || to the each call.
In similar way you actually could get rid of the position too, but that would in turn make the code shorter but much harder to read/understand.