Monday, September 7, 2009

Dynamically initialize 2D array in ruby

#!/usr/bin/ruby

class Array2D
def initialize(width, height)
@data = Array.new(width) { Array.new(height) }
end
def [](x, y)
@data[x][y]
end
def []=(x, y, value)
@data[x][y] = value
end
end

puts("please enter the size of square matrix")
$num=gets.chomp.to_i
arr = Array2D.new($num, $num)

for j in 0..$num-1

for k in 0..$num-1
arr[j, k] = 0
end
arr[j, k]= 0
end

No comments:

Post a Comment