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

陌路散爱 提交于 2019-12-21 04:45:07

问题


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

回答1:


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]]



回答2:


Either:

p x

-or-

require 'pp'

. . .        

pp x



回答3:


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



回答4:


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]] 



回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/7478300/how-do-i-print-a-multi-dimensional-array-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!