Let ruby output two-dimensional arrays in a matrix Style

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.