我有一个数组,我的目标是以如下方式打印代码:
``` 1 2 3 4 5 6 7 8 9 ```
我该怎么做呢?
``` 1 2 3 4 5 6 7 8 9 ```
我该怎么做呢?
我想有很多宝石可以用来做这件事,但如果您想自己动手,您可以按以下方式进行,以一个相当通用的方式:
您的输入由列标签组成:
col_labels = { date: "Date", from: "From", subject: "Subject" }
以及行的数据:
arr = [{date: "2014-12-01", from: "Ferdous", subject: "Homework this week"},
{date: "2014-12-01", from: "Dajana", subject: "Keep on coding! :)"},
{date: "2014-12-02", from: "Ariane", subject: "Re: Homework this week"}]
其中col_labels
和arr
的元素具有相同的键。
从这一点开始,代码是通用的。首先构造一个哈希表@columns
(我已经将其设置为实例变量以方便使用)。
@columns = col_labels.each_with_object({}) { |(col,label),h|
h[col] = { label: label,
width: [arr.map { |g| g[col].size }.max, label.size].max } }
# => {:date=> {:label=>"Date", :width=>10},
# :from=> {:label=>"From", :width=>7},
# :subject=> {:label=>"Subject", :width=>22}}
def write_header
puts "| #{ @columns.map { |_,g| g[:label].ljust(g[:width]) }.join(' | ') } |"
end
def write_divider
puts "+-#{ @columns.map { |_,g| "-"*g[:width] }.join("-+-") }-+"
end
def write_line(h)
str = h.keys.map { |k| h[k].ljust(@columns[k][:width]) }.join(" | ")
puts "| #{str} |"
end
:无需翻译,这是HTML标记中的段落元素。write_divider
write_header
write_divider
arr.each { |h| write_line(h) }
write_divider
+------------+---------+------------------------+
| Date | From | Subject |
+------------+---------+------------------------+
| 2014-12-01 | Ferdous | Homework this week |
| 2014-12-01 | Dajana | Keep on coding! :) |
| 2014-12-02 | Ariane | Re: Homework this week |
+------------+---------+------------------------+
如果您想要反转显示并将其变大,就像您的一样,请先执行:
$_!.reverse
$_@ += 4
最简单的方法是使用 table_print
gem: http://tableprintgem.com
例如,使用另一个答案中的数组,
your_array = [
{date: "2014-12-01", from: "Ferdous", subject: "Homework this week"},
{date: "2014-12-01", from: "Dajana", subject: "Keep on coding! :)"},
{date: "2014-12-02", from: "Ariane", subject: "Re: Homework this week"},
]
tp your_array
你将会得到以下结果:
DATE | FROM | SUBJECT
-----------|---------|-----------------------
2014-12-01 | Ferdous | Homework this week
2014-12-01 | Dajana | Keep on coding! :)
2014-12-02 | Ariane | Re: Homework this week
您还可以指定要包含的列(作为字符串或符号):
tp your_array, "subject", :from
当你的数组来自ActiveRecord查询,显示每一列都会使输出难以阅读时,这非常有用:
tp User.all, :full_name, :e-mail_address
您甚至可以访问相关的模型:
tp User.all, :full_name, "posts.title"
arr = [{date: "2014-12-01", from: "Ferdous", subject: "Homework this week"}, {date: "2014-12-01", from: "Dajana", subject: "Keep on coding! :)"}, {date: 2014-12-02, from: "Madonna", subject: "Re: Homework this week"}]
。 - Cary SwovelandActiveRecord
表吗?等等),以及关于你的代码的一些内容(例如相关类的示例)和你迄今为止所做的尝试。 - xlembourashirb
gem https://github.com/cldwalker/hirb - Philip Hallstrom