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
rust
use std::collections::HashMap; fn decode_component(input: &str) -> String { let bytes = input.as_bytes();
Parsing a URL query string in Rust
url-encoding
byte-parsing
iterators
Intermediate
8 steps
ruby
class CircuitBreaker class OpenCircuitError < StandardError; end def initialize(failure_threshold: 5, reset_timeout: 30, half_open_max: 1)
How a circuit breaker guards failing calls
state-machine
fault-tolerance
concurrency
Advanced
9 steps
rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FileKind { Png, Jpeg,
Detecting file types by magic bytes in Rust
pattern-matching
byte-slices
lookup-table
Intermediate
7 steps
ruby
class ProjectsController < ApplicationController before_action :set_project, only: %i[show update destroy] def create
Scoping a Rails API controller to Current.account
multitenancy
strong-parameters
nested-attributes
Intermediate
7 steps
ruby
class SearchController < ApplicationController def index @query = params[:q].to_s.strip end
Live search suggestions in a Rails controller
controllers
sql-injection
query-building
Intermediate
6 steps
ruby
class TasksController < ApplicationController before_action :set_project def reorder
Bulk task reordering with upsert_all in Rails
bulk-update
upsert
authorization
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.