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
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 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
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]]
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.