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
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.
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.
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.
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]]
Either:
p x
-or-
require 'pp'
. . .
pp x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With