在Ruby中将数组打印到表中

时间:2015-02-23 22:19:12

标签: ruby

所以,我的怀疑很简单。

我有一个数组,我的目标是以某种方式打印代码,以便输出以下内容:

Output Table

我该怎么做?

感谢。

1 个答案:

答案 0 :(得分:7)

我想有很多宝石可以做到这一点,但如果你想自己动手,你可以这样做,以一种相当普遍的方式:

您的输入由列标签组成:

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_labelsarr的元素具有相同的键。

从这一点开始,代码是通用的。首先构造一个哈希@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

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

Output Table