以表格形式输出哈希 [英] Output hash in a table-like format

查看:113
本文介绍了以表格形式输出哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将哈希输出到表中.数据具有名为students的数组,该数组具有键"first_name""last_name""grade_level"的散列.

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".

这是我的代码.

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?

推荐答案

可能应该使用 String#ljust String#rjust 助手在这里.

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

现在您可以打印它了:

puts titles, roster

以下是输出:

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.

这篇关于以表格形式输出哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆