Reputation: 245
So, I've got a script, say, program.rb, and in it I want to output the table_print version of an array of lists
['value1','value2','value3']
['value4','value4','value6']
so that it looks like this in the .txt file I output
col1 | col2 | col3
-------------------------------------------------------------------------
value1 | value2 | value3
.
.
.
I already have table_print installed, but this is all I have so far as a working model:
require 'table_print'
TABLEPRINT STUFF?
open('table_print_output.txt','a'){|g|
g.puts TABLEPRINT?
}
I guess I'm just not getting how to do the Ruby equivalent of MySQL's create table
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
)
and insert into
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
And I don't want a temporary/latent database just sitting around for no reason. It's like I need a database as a variable or something; that is, I create it, I populate it, I print it, I destroy it.
Upvotes: 1
Views: 623
Reputation: 114138
table_print
can't print nested arrays like this:
arrays = [
['value1', 'value2', 'value3'],
['value4', 'value5', 'value6']
]
because it flattens the input. You have to convert the inner arrays to another object.
Hash
would work:
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
Struct
would work as well:
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
Upvotes: 1
Reputation: 6076
Looks like you need 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
Upvotes: 1