The Ruby pp () function can be used to output arrays in a very beautiful way. However, the disadvantage is that the two-dimensional array is displayed on one row. We want it to be output in the form of a subarray per row, as shown in
Is it more Pretty?
In fact, PP is a very good framework for output objects (although it seems to be written in Japan ). To achieve the above effect, you only need to add a line of code in the default Implementation of the Array # pretty_print () function! The Code is as follows (the file name is "pp_extension.rb"): 1 # Outputs two-dimension array like matrix
2 class Array
3 def pretty_print (q)
4 q. group (1, '[', ']') {
5 q. seplist (self) {| v |
6 q. current_group.break if v. is_a? (Array )&&! Q. current_group.first? # Added by me
7 q. pp v
8}
9}
10 end
11end
Do you think I understand the implementation principles of PrettyPrint and PP? Actually not. I just roughly read the source code of these two classes (they are in C: \ ruby \ lib \ ruby \ 1.8 \), and then I guess its implementation method is to use group () the function groups the information in the object, and recursively calls the pp () function to output the information of each group. Then I copied the default Implementation of the Array # pretty_print () function and tried to make some modifications. Therefore, I have no way to analyze the implementation method of PP in detail. I hope this article will bring you some inspiration and serve as a reference. Maybe I will take a closer look at their source code later.
PS: You can use the modified pp () to output a 3D array. You can try it.