Skip to content

Instantly share code, notes, and snippets.

@shuuuuun
Last active March 18, 2023 09:14
Show Gist options
  • Save shuuuuun/d62792229e4c6b62acdbf06c302b2450 to your computer and use it in GitHub Desktop.
Save shuuuuun/d62792229e4c6b62acdbf06c302b2450 to your computer and use it in GitHub Desktop.
さくっとhashをテーブル出力したいときに使うやつ
class TablePrinter
# Initialize data
# @param data [Array] printing data as array of hash.
# @param labels [Hash] column labels hash.
# @example
# data = [
# { name: "foo", installed_versions: ["5.15.5_3"], current_version: "5.15.7" },
# { name: "bar", installed_versions: ["7.0.4"], current_version: "7.0.5" },
# { name: "baz", installed_versions: ["3.2.5"], current_version: "3.2.7" },
# ]
# labels = {
# name: "Name",
# installed_versions: "Installed Versions",
# current_version: "Current Version",
# }
# TablePrinter.new(data, labels)
def initialize(data, labels)
@data = data.map{ _1.map{ |k,v| [k.to_sym, v.is_a?(Array) ? v.join(", ") : v.to_s ]}.to_h }
@columns = labels.each_with_object({}) do |(col, label), memo_obj|
memo_obj[col.to_sym] = { label: label, width: [@data.map{ _1[col.to_sym]&.size || 0 }.max, label.size].max }
end
end
# Print table
def print
write_divider
write_header
write_divider
@data.each{ write_line(_1) }
write_divider
end
private
def write_header
$stdout.puts "| #{ @columns.map{ |_k,v| v[:label].ljust(v[:width]) }.join(" | ") } |"
end
def write_divider
$stdout.puts "+-#{ @columns.map{ |_k,v| "-"*v[:width] }.join("-+-") }-+"
end
def write_line(line)
keys = @columns.keys
str = keys.map{ |k| line[k].ljust(@columns.dig(k, :width) || 0) }.join(" | ")
$stdout.puts "| #{str} |"
end
end
# thanks: https://stackoverflow.com/a/28685559
# Example:
data = [
{ name: "foo", installed_versions: ["5.15.5_3"], current_version: "5.15.7" },
{ name: "bar", installed_versions: ["7.0.4"], current_version: "7.0.5" },
{ name: "baz", installed_versions: ["3.2.5"], current_version: "3.2.7" },
]
labels = {
name: "Name",
installed_versions: "Installed Versions",
current_version: "Current Version",
}
tp = TablePrinter.new(data, labels)
tp.print
# +------+--------------------+-----------------+
# | Name | Installed Versions | Current Version |
# +------+--------------------+-----------------+
# | foo | 5.15.5_3 | 5.15.7 |
# | bar | 7.0.4 | 7.0.5 |
# | baz | 3.2.5 | 3.2.7 |
# +------+--------------------+-----------------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment