ruby
41 lines · 7 steps
Turning records into CSV in Ruby
A small class that renders a list of hashes into CSV with derived headers and typed value formatting.
Explained by
highlit
1require "csv"
2
3class CsvExporter
4 def initialize(records, columns: nil)
5 @records = records
6 @columns = columns || derive_columns(records)
7 end
8
9 def to_csv
10 CSV.generate do |csv|
11 csv << @columns.map { |col| humanize(col) }
12 @records.each do |record|
13 csv << @columns.map { |col| format_value(record[col]) }
14 end
15 end
16 end
17
18 def write(path)
19 File.write(path, to_csv)
20 end
21
22 private
23
24 def derive_columns(records)
25 records.flat_map(&:keys).uniq
26 end
27
28 def humanize(key)
29 key.to_s.tr("_", " ").split.map(&:capitalize).join(" ")
30 end
31
32 def format_value(value)
33 case value
34 when Time, DateTime then value.iso8601
35 when Date then value.strftime("%Y-%m-%d")
36 when Array then value.join("; ")
37 when nil then ""
38 else value.to_s
39 end
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deriving columns from the data lets an exporter handle records with varying keys without hard-coded configuration.
- 2Centralizing value formatting in one method keeps every cell consistently serialized regardless of type.
- 3CSV.generate builds a string incrementally, so the same logic serves both in-memory output and file writing.
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
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 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/turning-records-into-csv-in-ruby-explained-ruby-6d61/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.