ruby
39 lines · 8 steps
Parsing a .env file in Ruby
A small Dotenv module reads key=value lines, unquotes values, and loads them into ENV without clobbering existing variables.
Explained by
highlit
1module Dotenv
2 LINE = /\A\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*\z/
3
4 module_function
5
6 def load(path = ".env", overwrite: false)
7 File.foreach(path, chomp: true).each_with_object({}) do |line, parsed|
8 next if line.strip.empty? || line.strip.start_with?("#")
9
10 match = line.match(LINE) or next
11 key, raw = match.captures
12 value = unquote(raw)
13
14 parsed[key] = value
15 ENV[key] = value if overwrite || !ENV.key?(key)
16 end
17 end
18
19 def unquote(raw)
20 case raw
21 when /\A"(.*)"\z/m
22 unescape(Regexp.last_match(1))
23 when /\A'(.*)'\z/m
24 Regexp.last_match(1)
25 else
26 strip_inline_comment(raw)
27 end
28 end
29
30 def unescape(value)
31 value.gsub(/\\([nrt\\"])/) do
32 { "n" => "\n", "r" => "\r", "t" => "\t", "\\" => "\\", '"' => '"' }.fetch($1)
33 end
34 end
35
36 def strip_inline_comment(value)
37 value.sub(/\s+#.*\z/, "").strip
38 end
39end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single anchored regex with capture groups cleanly splits structured text into named parts.
- 2Handling quoted, single-quoted, and bare values separately lets you apply the right escaping rules to each.
- 3Guarding writes with overwrite || !ENV.key?(key) keeps existing environment values authoritative by default.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 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
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
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
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/parsing-a-env-file-in-ruby-explained-ruby-dea1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.