Mubarak Mubarak - 6 months ago 9
Ruby Question

Ruby nomethoderror for multidimensional array

I am working on Ruby program where I am creating wordsearch puzzle. I have 10x10 double array "

arr
" and I use a method to find a random starting position (example:
arr[5][9]
), then I choose a direction but I am having problem where it goes out of bounds.

Example: one of the words that needs to be placed into puzzle is "dog". I get starting position
arr[5][9]
and iterate through "dog", placing it in the array horizontally one letter at a time. So
arr[5][9]
is "d",
arr[5][10]
is "o", but when it try to place "g" my program crashes and I get error saying "
no method [] for nil: nil class (no method error)
". I know that this is because it is going out of bounds, but how can I stop it from doing that? thank you

edit: If the word can not fit, I want my program to choose a new starting position until the word can fit. I also want to prevent it from going out of bounds

Answer

If you have a 10 x 10 array then all indexes should be between 0 and 9. You need to guarantee that the word will not exceed the bounds of the array in either dimension.

So if you have a word dog, for example, then the starting index must be between 0 and 7.

Here is a method you can use for this, with examples of it being called:

2.3.0 :005 > def random_x_value(word)
2.3.0 :006?>   (0..(10-word.length)).to_a.sample
2.3.0 :007?>   end
 => :random_x_value
2.3.0 :008 > 10.times { puts random_x_value('dog') }
5
0
2
5
2
3
6
0
2
0
 => 10