Sunday, 29 September 2013

using elements of one ruby array as indices to another

using elements of one ruby array as indices to another

Still struggling with my first ruby program. In the following code, I am
trying to get the index from each time a certain letter, 'guess', appears
in array 'secret_word' and then using those indices to insert the same
letter into another array, 'user_word', without disturbing any of the
other letters that might already be in user_word. I decided to store the
indices selected from 'secret_word' in an array, 'indices'. The error
message implies that each element of indices is an array, not a fixnum as
expected. Bottom line, it will not let me use the element from indices to
index into user_word. Help?
if secret_word.include?(guess) #secret_word is an array of chars. guess is
a char.
indices = Array.new
indices<< secret_word.each_index.select{ |letter| secret_word[letter] ==
guess } #verified that this array fills correctly
indices.each do |e|
user_word[e] = guess
end
end
I have tried variations on the innermost block but to no avail

No comments:

Post a Comment