Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difficulty modifying two dimensional ruby array

Excuse the newbie question. I'm trying to create a two dimensional array in ruby, and initialise all its values to 1. My code is creating the two dimensional array just fine, but fails to modify any of its values.

Can anyone explain what I'm doing wrong?

  def mda(width,height)
     #make a two dimensional array
     a = Array.new(width)
     a.map! { Array.new(height) }

     #init all its values to 1
     a.each do |row|
       row.each do |column|
          column = 1
       end
     end
     return a
  end
like image 274
WoodenKitty Avatar asked Jul 24 '26 07:07

WoodenKitty


1 Answers

It the line row.each do |column| the variable column is the copy of the value in row. You can't edit its value in such way. You must do:

def mda(width,height)
  a = Array.new(width)
  a.map! { Array.new(height) }
  a.each do |row|
    row.map!{1}
  end
  return a
end

Or better:

def mda(width,height)
  a = Array.new(width)
  a.map! { Array.new(height) }

  a.map do |row|
    row.map!{1}
  end
end

Or better:

def mda(width,height)
  a = Array.new(width){ Array.new(height) }
  a.map do |row|
    row.map!{1}
  end
end

Or better:

def mda(width,height)
  Array.new(width) { Array.new(height){1} }
end
like image 94
Nakilon Avatar answered Jul 26 '26 02:07

Nakilon