Output hash in a table-like format

2020-07-24 06:56发布

问题:

I need to output my hashes to a table. The data have an array called students, which has hashes with keys "first_name", "last_name", and "grade_level".

This is the code I have.

students = []

# Dummy Inputs.
students = [
  {
      "first_name" => "Bob",
      "last_name" => "Builder",
      "grade_level" => 4
      },
  {
      "first_name" => "Test",
      "last_name" => "Buida",
      "grade_level" => 3
      },
  {
      "first_name" => "Senior",
      "last_name" => "June",
      "grade_level" => 5
      },
  {
      "first_name" => "John",
      "last_name" => "Smith",
      "grade_level" => 2
      },
  {
      "first_name" => "Me",
      "last_name" => "Developer",
      "grade_level" => 11
      }]

...

puts "\n--------------- \n" +
          "| CLASS ROSTER \n" +
          "--------------- \n"  # Felt lazy to add them individual put
    puts "First Name    Last Name    Grade Level\n"

    students.each do |student|
      puts "#{student["first_name"]}        #{student["last_name"]}     #{student["grade_level"]}"

I used tab to set the column. Sometimes, it glitches like below.

Is there any way to make this better?

回答1:

One probably should make use of String#ljust and String#rjust helpers here.

First of all, let’s prepare the output:

FIELD_SIZE = 20
roster =
  students.map do |s|
    s.values.map do |f|
      f.to_s.ljust(FIELD_SIZE) # 1 row
    end.join('   ')            # join columns with spaces
  end.join($/)                 # join rows with OS-dependent CR/LF
titles =
  ['First Name', 'Last Name', 'Grade Level'].map do |t|
    t.to_s.ljust(FIELD_SIZE)
  end.join(' | ')              # join with bars

Now you can print it:

puts titles, roster

Here is the output:

First Name           | Last Name            | Grade Level         
Bob                    Builder                4                   
Test                   Buida                  3                   
Senior                 June                   5                   
John                   Smith                  2                   
Me                     Developer              11   

Feel free to change the joiners and field size to see how it works.



标签: ruby hash