1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-06 16:48:01 +00:00

Add Print Data To Formatted Table as a Ruby TIL

This commit is contained in:
jbranchaud
2023-11-28 12:01:38 -06:00
parent 5bcd67946c
commit 4edc43e4bb
2 changed files with 54 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1350 TILs and counting..._
_1351 TILs and counting..._
---
@@ -1114,6 +1114,7 @@ _1350 TILs and counting..._
- [Pattern Match Values From A Hash](ruby/pattern-match-values-from-a-hash.md)
- [Percent Notation](ruby/percent-notation.md)
- [Precedence Of Logical Operators](ruby/precedence-of-logical-operators.md)
- [Print Data To Formatted Table](ruby/print-data-to-formatted-table.md)
- [Question Mark Operator](ruby/question-mark-operator.md)
- [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md)
- [Read The First Line From A File](ruby/read-the-first-line-from-a-file.md)

View File

@@ -0,0 +1,52 @@
# Print Data To Formatted Table
Often when I'm doing some debugging or reporting from the Ruby/Rails console, I
end up with a chunk of data that I'd like to share. Usually I'd like something
that I can copy into the text area of Slack or a project management tool.
Copying and pasting a pretty-printed hash isn't bad, but a nicely formatted
table would be even better.
Here is a small method I can copy and paste into the console:
```ruby
def print_to_table(headings, data)
# Calculate column widths
column_widths = headings.each_with_index.map do |heading, index|
[heading.size, *data.map { |row| row[index].to_s.size }].max
end
# Method to format a row
def format_row(row, widths)
row.each_with_index.map { |item, index| item.to_s.ljust(widths[index]) }.join(" | ")
end
# Print headings
puts format_row(headings, column_widths)
puts "-" * column_widths.sum + "-" * (column_widths.size * 3 - 3)
# Print data
data.each do |row|
puts format_row(row, column_widths)
end
end
```
And then I can run it like so to get formatted table that can be copy-pasted
elsewhere:
```ruby
> headings = [:id, :name, :role]
=> [:id, :name, :role]
> data = [
[123, 'Bob', 'Burger flipper'],
[456, 'Linda', 'Server'],
[789, 'Gene', 'Ketchup Refiller']
]
=> [[123, "Bob", "Burger flipper"], [456, "Linda", "Server"], [789, "Gene", "Ketchup Refiller"]]
> print_to_table(headings, data)
# id | name | role
# ------------------------------
# 123 | Bob | Burger flipper
# 456 | Linda | Server
# 789 | Gene | Ketchup Refiller
```