Efe Imoloame
Efe Imoloame

Reputation: 109

How do I loop through nested arrays in ruby?

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'

Upvotes: 0

Views: 1775

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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

Upvotes: 1

Amadan
Amadan

Reputation: 198324

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!

Upvotes: 2

Related Questions