ruby
35 lines · 8 steps
Rendering an ASCII table in Ruby
Turn an array of row hashes into an aligned, bordered text table by measuring column widths first.
Explained by
highlit
1def render_table(rows)
2 return "(no data)" if rows.empty?
3
4 columns = rows.flat_map(&:keys).uniq
5 widths = columns.each_with_object({}) do |col, acc|
6 cell_lengths = rows.map { |row| stringify(row[col]).length }
7 acc[col] = [col.to_s.length, *cell_lengths].max
8 end
9
10 separator = "+" + columns.map { |col| "-" * (widths[col] + 2) }.join("+") + "+"
11 header = format_row(columns.map { |col| [col, col.to_s] }, widths)
12
13 lines = [separator, header, separator]
14 rows.each do |row|
15 cells = columns.map { |col| [col, stringify(row[col])] }
16 lines << format_row(cells, widths)
17 end
18 lines << separator
19
20 lines.join("\n")
21end
22
23def format_row(cells, widths)
24 padded = cells.map { |col, value| " #{value.ljust(widths[col])} " }
25 "|" + padded.join("|") + "|"
26end
27
28def stringify(value)
29 case value
30 when nil then ""
31 when Hash then value.map { |k, v| "#{k}=#{stringify(v)}" }.join(", ")
32 when Array then value.map { |v| stringify(v) }.join(", ")
33 else value.to_s
34 end
35end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Measure every column's maximum width before drawing so all cells align consistently.
- 2Collecting keys across all rows lets you handle rows with differing shapes.
- 3A recursive stringifier gives you predictable cell text for nested values like hashes and arrays.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/rendering-an-ascii-table-in-ruby-explained-ruby-6ce2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.