Ruby on rails 如何在Ruby脚本中编写table_打印输出?

Ruby on rails 如何在Ruby脚本中编写table_打印输出?,ruby-on-rails,ruby,formatting,Ruby On Rails,Ruby,Formatting,所以,我有一个脚本,比如program.rb,我想在其中输出列表数组的版本 ['value1','value2','value3'] ['value4','value4','value6'] 所以在我输出的.txt文件中看起来是这样的 col1 | col2 | col3 ------------------------------------------------------------------------- value1

所以,我有一个脚本,比如program.rb,我想在其中输出列表数组的版本

['value1','value2','value3']
['value4','value4','value6']
所以在我输出的.txt文件中看起来是这样的

  col1              | col2              | col3
  -------------------------------------------------------------------------
  value1            | value2            | value3
  .
  .
  .
我已经安装了table_print,但就工作模型而言,我只有这些:

require 'table_print'

TABLEPRINT STUFF?

open('table_print_output.txt','a'){|g|
    g.puts TABLEPRINT?
}
我想我只是不知道如何做与MySQL的createtable相当的Ruby

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
并插入

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

我不希望一个临时/潜在的数据库无缘无故地坐在那里。这就像我需要一个数据库作为变量或其他东西;也就是说,我创建它,我填充它,我打印它,我销毁它。

看起来您需要
String\ljust

rows = [
  ['value1','value2','value3'],
  ['value4','value4','value6']
]

rows.each do |row|
  puts "#{row[0].ljust(30)}|#{row[1].ljust(30)}|#{row[2].ljust(30)}"
end

table\u print
无法像这样打印嵌套数组:

arrays = [
  ['value1', 'value2', 'value3'],
  ['value4', 'value5', 'value6']
]
因为它使输入变得平坦。您必须将内部数组转换为另一个对象

将工作:

hashes = array.map { |values| %w(col1 col2 col3).zip(values).to_h }
#=> [
#     {"col1"=>"value1", "col2"=>"value2", "col3"=>"value3"},
#     {"col1"=>"value4", "col2"=>"value5", "col3"=>"value6"}
#   ]

tp hashes
# COL1   | COL2   | COL3
# -------|--------|-------
# value1 | value2 | value3
# value4 | value5 | value6
也会起作用:

Row = Struct.new(:col1, :col2, :col3)
rows = arrays.map { |values| Row.new(*values) }
#=> [
#     #<struct Row col1="value1", col2="value2", col3="value3">,
#     #<struct Row col1="value4", col2="value5", col3="value6">
#   ]

tp rows
# COL1   | COL2   | COL3
# -------|--------|-------
# value1 | value2 | value3
# value4 | value5 | value6
Row=Struct.new(:col1,:col2,:col3)
rows=arrays.map{| values | Row.new(*values)}
#=> [
#     #,
#     #
#   ]
tp行
#COL1 | COL2 | COL3
# -------|--------|-------
#值1 |值2 |值3
#价值4 |价值5 |价值6

请尝试为姓名和电子邮件地址留出更多空间。除非你有非常令人信服的理由来限制某些东西,否则使用
VARCHAR(255)
作为默认值。是的,我知道,我使用VARCHAR(255),我只是复制了它作为一个例子。