Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out 2D array

array = Array.new(10) { Array.new(10 , 0)}

array.each { |x| print x }

Prints out one single line of ten [0, 0, 0, 0, 0, 0, 0, 0, 0, 0].

If I were to change print to puts, I then get 100 0 down the page.

How do I print out each array on a separate line without the "[]" and ","?

Something like:

0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
like image 949
ChatNoir Avatar asked Dec 05 '14 13:12

ChatNoir


2 Answers

Suppose:

arr = Array.new(10) { (0..20).to_a.sample(10) }

Then

puts arr.map { |x| x.join(' ') }
1 9 6 15 7 19 18 3 0 12
13 20 18 15 0 3 19 1 14 16
7 16 5 3 12 19 4 9 20 10
6 10 9 1 18 17 7 19 5 15
12 3 8 16 10 5 2 18 20 6
12 9 0 18 2 11 16 8 7 15
8 9 14 19 3 16 6 20 13 17
7 19 16 14 13 6 9 2 3 5
10 17 8 15 11 2 13 14 16 7
14 9 20 17 15 3 4 2 11 19

is not very, er, attractive. For something more pleasing, you could quite easily do something like this:

width = arr.flatten.max.to_s.size+2
  #=> 4
puts arr.map { |a| a.map { |i| i.to_s.rjust(width) }.join }
   1   9   6  15   7  19  18   3   0  12
  13  20  18  15   0   3  19   1  14  16
   7  16   5   3  12  19   4   9  20  10
   6  10   9   1  18  17   7  19   5  15
  12   3   8  16  10   5   2  18  20   6
  12   9   0  18   2  11  16   8   7  15
   8   9  14  19   3  16   6  20  13  17
   7  19  16  14  13   6   9   2   3   5
  10  17   8  15  11   2  13  14  16   7
  14   9  20  17  15   3   4   2  11  19

If you have too many columns to display on the screen you can do this:

puts arr.map { |a| a.map { |i| i.to_s.rjust(width) }.join.tinyfy }
    1   9   6  15   7  19  18   3   0  12
   13  20  18  15   0   3  19   1  14  16
    7  16   5   3  12  19   4   9  20  10
    6  10   9   1  18  17   7  19   5  15
   12   3   8  16  10   5   2  18  20   6
   12   9   0  18   2  11  16   8   7  15
    8   9  14  19   3  16   6  20  13  17
    7  19  16  14  13   6   9   2   3   5
   10  17   8  15  11   2  13  14  16   7
   14   9  20  17  15   3   4   2  11  19
like image 96
Cary Swoveland Avatar answered Sep 20 '22 02:09

Cary Swoveland


Try join:

array.each { |x|
 puts x.join(" ")
}
# prints:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
like image 44
shivam Avatar answered Sep 19 '22 02:09

shivam