I'm creating a grid using a 2-d array and i want to put different values in it I have tried:
grid =(Array.new(10,Array.new(10," ") ))
for row in rand(1..9)
for column in rand(1..9)
grid[row][column] == 'a'
grid = Array.new(10) { Array.new(10, "") }
otherwise you'll get the same array repeated 10 times, which is presumably not what you want.
I am not sure what you want to do with your iterations. Do note that Ruby arrays are 0-indexed, so a 10-element array will have an index in 0...9. Also note that iteration over an array is usually done with each, as Carpetsmoker notes in comments:
grid.each do |row|
row.each_index do |index|
row[index] = "abcde"[rand(5)]
end
end
EDIT: Thanks Cary!
Your question is not clear. If you want to put the letter 'a' at n random locations in grid, you could do this:
def salt(grid, obj, n)
m = grid.size
locs = (0...m*m).to_a.sample(n)
locs.each do |l|
row, col = l.divmod(m)
grid[row][col] = obj
end
end
grid = Array.new(10) { Array.new(10, ' ') }
salt(grid,'a',30)
grid
#=> [[" ", "a", " ", " ", "a", "a", "a", " ", " ", " "],
# ["a", "a", " ", "a", "a", " ", " ", "a", " ", " "],
# [" ", "a", " ", " ", "a", " ", " ", " ", "a", " "],
# [" ", " ", " ", "a", " ", " ", "a", " ", " ", "a"],
# [" ", " ", " ", "a", " ", " ", " ", " ", " ", " "],
# [" ", " ", "a", " ", " ", " ", " ", " ", " ", " "],
# ["a", " ", " ", " ", " ", " ", "a", " ", " ", "a"],
# [" ", " ", "a", " ", " ", "a", " ", "a", " ", " "],
# [" ", "a", " ", " ", "a", " ", " ", " ", "a", "a"],
# [" ", " ", "a", "a", "a", " ", " ", " ", " ", " "]]
You could instead write:
locs = n.times.map { rand(m*m) }
but that will likely result in some duplicates, in which case fewer than n cells will be filled with "a"'s. For example, when I computed locs that way for n=30 I found:
locs.uniq.size
#=> 27
rand(1..9).each { |row| ... }; no one usesforin Ruby except those unfamiliar with it :-)p rand(1..9), you will see that it doesn't give you an array, but a random integer within that range. You cannot loop over integers. They also don't have "each" method. They are not enumerables.grid[0][0]='X'; p gridand you'll see what I mean. It's defined correctly in the answers.