Reputation: 13004
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
Upvotes: 8
Views: 18974
Reputation: 801
If you want to take your multi-dimensional array and present it as a visual representation of a two dimensional graph, this works nicely:
x.each do |r|
puts r.each { |p| p }.join(" ")
end
Then you end with something like this in your terminal:
1 2 3
4 5 6
7 8 9
Upvotes: 6
Reputation: 35298
The 'fundamental' way to do this, and the way that IRB does it, is to print the output of #inspect
:
ruby-1.9.2-p290 :001 > x = [ [1, 2, 3], [4, 5, 6]]
=> [[1, 2, 3], [4, 5, 6]]
ruby-1.9.2-p290 :002 > x.inspect
=> "[[1, 2, 3], [4, 5, 6]]"
pp
produces slightly nicer output, however.
Upvotes: 2
Reputation: 10004
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]]
Upvotes: 14
Reputation: 7598
PrettyPrint, which comes with Ruby, will do this for you:
require 'pp'
x = [ [1, 2, 3], [4, 5, 6]]
pp x
However the output in Ruby 1.9.2 (which you should try to use, if possible) does this automatically:
ruby-1.9.2-p290 :001 > x = [ [1, 2, 3], [4, 5, 6]]
=> [[1, 2, 3], [4, 5, 6]]
ruby-1.9.2-p290 :002 > p x
[[1, 2, 3], [4, 5, 6]]
=> [[1, 2, 3], [4, 5, 6]]
Upvotes: 4
Reputation: 160181
Iterate over each entry in the "enclosing" array. Each entry in that array is another array, so iterate over that as well. Print. Or, use join
.
arr = [[1, 2, 3], [4, 5, 6]]
arr.each do |inner|
inner.each do |n|
print n # Or "#{n} " if you want spaces.
end
puts
end
arr.each do |inner|
puts inner.join(" ") # Or empty string if you don't want spaces.
end
Upvotes: 2