Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

26 lines (21 sloc) 0.67 kb
################################################################################
# 11.04a_matrix.rb
#
# how to make matrix with array
################################################################################
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
p a[1][2] #=> 6
# following initialize has issue
a = Array.new(3, [0, 0, 0])
p a #=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[0][1] = 2
p a #=> [[0, 2, 0], [0, 2, 0], [0, 2, 0]] !!all arrays are changed!!
# following initialize is ideal
a = Array.new(3) {
[0, 0, 0]
}
p a #=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[0][1] = 2
p a #=> [[0, 2, 0], [0, 0, 0], [0, 0, 0]]
a = Array.new(5){|i| i + 1}
p a #=> [1, 2, 3, 4, 5]
Jump to Line
Something went wrong with that request. Please try again.