How to print a multidimensional array in ruby?

What is the preferred method for printing a multidimensional array in a ruby?

For example, suppose I have this 2D array:

x = [ [1, 2, 3], [4, 5, 6]] 

I am trying to print it:

 >> print x 123456 

And what does not work:

 >> puts x 1 2 3 4 5 6 
+6
source share
6 answers

If you're just looking for debugging output that is easy to read, "p" is useful (it calls validation () in the array)

 px [[1, 2, 3], [4, 5, 6]] 
+12
source

Or:

 px 

-or -

 require 'pp' . . . pp x 
+7
source

If you want to take your multidimensional array and present it as a visual representation of a two-dimensional graph, this works great:

 x.each do |r| puts r.each { |p| p }.join(" ") end 

Then you end up with something like this in the terminal:

  1 2 3 4 5 6 7 8 9 
+5
source

PrettyPrint that 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 > px [[1, 2, 3], [4, 5, 6]] => [[1, 2, 3], [4, 5, 6]] 
+4
source

The "main" way to do this and how the 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 a slightly nicer conclusion.

+2
source

Iterate over each record in the array enclosing. Each entry in this array is another array, so iterating over it. Print out. 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 
+1
source

Source: https://habr.com/ru/post/897644/


All Articles