Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a multi-dimensional array in ruby?

What's the preferred method of printing a multi-dimensional array in ruby?

For example, suppose I have this 2D array:

x = [ [1, 2, 3], [4, 5, 6]]

I try to print it:

>> print x
123456

Also what doesn't work:

>> puts x
1
2
3
4
5
6
like image 272
dsg Avatar asked Sep 19 '11 23:09

dsg


People also ask

How do you print a multi-dimensional array?

To print the content of a one-dimensional array, use the Arrays. toString() method. To print the content of a a multi-dimensional array, use the Arrays. deepToString() method.

How do you print an array in Ruby?

Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.

How are multidimensional arrays accessed?

Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes. Example: int x[2][1]; The above example represents the element present in the third row and second column.


2 Answers

If you're just looking for debugging output that is easy to read, "p" is useful (it calls inspect() on the array)

p x
[[1, 2, 3], [4, 5, 6]]
like image 96
spike Avatar answered Sep 19 '22 06:09

spike


Either:

p x

-or-

require 'pp'

. . .        

pp x
like image 36
DigitalRoss Avatar answered Sep 18 '22 06:09

DigitalRoss