gpt4 book ai didi

ruby - 以类似表格的格式输出散列

转载 作者:数据小太阳 更新时间:2023-10-29 08:57:18 25 4
gpt4 key购买 nike

我需要将哈希值输出到表中。数据有一个名为 students 的数组,它的散列键为 "first_name""last_name""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"]}"

我用tab来设置列。有时,它会出现如下故障。

sample output

有什么办法可以让它变得更好吗?

最佳答案

一个人可能应该利用 String#ljustString#rjust这里有 helper 。

首先,让我们准备输出:

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

随意更改连接器和字段大小以查看其工作原理。

关于ruby - 以类似表格的格式输出散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com