8

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
  • Oh, I thought you meant as a grid. Never mind. Commented Sep 19, 2011 at 23:17

6 Answers 6

14

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]]
Sign up to request clarification or add additional context in comments.

Comments

7

Either:

p x

-or-

require 'pp'

. . .        

pp x

1 Comment

+1 for mentioning 'pp', which I didn't even know existed. It seems to do the same thing as inspect for this example on ruby 1.9.2 though.
6

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

2 Comments

what's the use of .map { |p| p } ?!
thanks for the note. you could do each instead of map. I will edit the sample to use each since it's more appropriate for this purpose.
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]] 

Comments

2

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.