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
class OrderMailerPreview < ActionMailer::Preview def confirmation OrderMailer.confirmation(sample_order) end
Previewing Rails mailers with sample data
mailer-previews
test-fixtures
in-memory-objects
Beginner
6 steps
typescript
type Masker = (value: string) => string; const maskEmail: Masker = (value) => { const [local, domain] = value.split("@");
Recursively masking sensitive data for logs
recursion
regex
data-masking
Intermediate
9 steps
ruby
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
ruby
require 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
ruby
class HashDiff Change = Struct.new(:from, :to) def self.call(before, after)
Diffing two hashes in Ruby
set-operations
struct
enumerable
Intermediate
7 steps
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 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.