Created
October 19, 2020 10:21
-
-
Save rhydlewis/bce2f12b5c3923cdfe187bbd9e76b873 to your computer and use it in GitHub Desktop.
Ruby code to convert table of data copied from spreadsheet into a Markdown table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
query = ARGV[0] # Alfred | |
if query | |
col_sep = query | |
else | |
col_sep = "\t" | |
end | |
clipboard = `pbpaste` | |
rows = CSV.parse(clipboard, col_sep: col_sep) | |
column_widths = [] | |
markdown_rows = [] | |
separators = "" | |
rows.each { |row| | |
row.each_with_index { |cell, x| | |
if column_widths[x] | |
column_widths[x] = cell.length if cell.length > column_widths[x] | |
else | |
column_widths[x] = cell.length | |
end | |
} | |
} | |
rows.each { |row | | |
markdown = "| " | |
row.each_with_index { |cell, index| | |
suffix = " " * (column_widths[index] - cell.length + 1) | |
markdown += cell + suffix + "| " | |
} | |
markdown_rows << markdown.strip() | |
} | |
column_widths.each { |width| | |
separators << "|" + ("-" * (width + 2)) | |
} | |
separators += "|" | |
markdown_rows.insert(1,separators) | |
print markdown_rows.join("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment