whoami
Lucas Jenß
cat /etc/motd
The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.
ls -la ~/languages/
- drwxr-xr-x
- ▶ PHP
- ▶ Ruby
- ▶ Scala
- ▶ C#
- ▶ JavaScript
- ▶ Objective-C
- ▶ Shell Scripting
ls -la ~/toolchain/
- drwxr-xr-x
- ▶ Typo3
- ▶ Akka
- ▶ Capistrano
- ▶ Git
- ▶ MAMP
- ▶ Adobe Illustrator
- ▶ NSTrackingArea (Cocoa)
uname -a
- drwxr-xr-x
- ▶ Mac OS X
- ▶ Unix
Optimizing Ruby array operations with each_with_object
Ruby developers often meet a familiar bottleneck when a large array must become an index, grouped summary, or lookup map. A loop that appends to several intermediate collections may spend more time allocating objects than the business logic suggests. Replacing that sprawl with one explicit accumulator makes the data flow easier to inspect and can improve throughput without changing the result.
each_with_object is an Enumerable method that passes each element and the accumulator to a block, then returns the accumulator rather than the source array. That return contract makes it a better fit than each for building a derived collection. It does not make the traversal automatically fast, but it makes allocation and data flow easier to inspect.
Many Australian product teams in Sydney, Melbourne, and Brisbane still use Ruby and Rails, particularly in e-commerce, SaaS, and agency work. Their everyday rhythm often mixes office stand-ups, remote pairing, and small code-review sessions, so a reproducible benchmark is more valuable than a quick test on one laptop. Local scheduling also matters: Sydney and Melbourne change clocks for daylight saving, while Brisbane does not, which can move an overnight batch window twice a year.
Understand the accumulator contract
The accumulator is the key to the method's behaviour. Pass the object that should hold intermediate state, and the block receives both the current item and that object. This avoids hidden outer variables and makes the mutation visible at the call site.
rows.each_with_object({}) do |row, index|
index[row[:id]] = row
end
Because the method returns the accumulator, the result can be assigned immediately without rescuing a value from a closure. each returns the original receiver, which is rarely useful when the purpose is aggregation. map, by contrast, allocates an output array even if the desired result is a hash or a set of unique values.
Keep the block narrow and let it perform one transformation. A broader notebook of experiments and implementation observations is available through Nix Mash development notes, which can provide a useful reference while reproducing behaviour outside the application. In particular, do not allocate a temporary array for every row merely to append one value to the accumulator.
Match the data structure to the result
Choose the result shape before choosing the loop. A hash keyed by record identifier supports constant-time lookup later, while an array of grouped records preserves duplicates. The block should make that choice obvious.
groups = rows.each_with_object({}) do |row, result|
(result[row[:category]] ||= []) << row
end
The assignment to result[row[:category]] ||= [] creates a bucket only when a category is first encountered. That is usually preferable to pre-populating every key with an empty array. For indexed data, assigning directly means a later duplicate identifier replaces the earlier row; use nested arrays or a two-pass strategy when duplicates must remain distinguishable.
Use map when every source element should yield a transformed element, filter_map when transformed nil values should be discarded, and each_with_object when many inputs feed one evolving structure. These methods can share the same block count and asymptotic complexity, yet their allocation profiles differ enough to matter when records number in the hundreds of thousands.
Compare methods with realistic benchmarks
There is no universally fastest collection method, because speed depends on the output, payload size, duplicate rate, and runtime version. Compare approaches that produce equivalent results, and include object allocation in the assessment. A method that looks quicker in wall-clock time can still create enough garbage to slow a long-running worker.
| Method | Returned value | Allocation pattern | Strongest fit |
|---|---|---|---|
each |
Original receiver | No derived collection | Side effects only |
map |
Array of every mapped value | One output array | One-to-one transformation |
reduce or inject |
Accumulator | One mutable result | Flexible folds |
each_with_object |
Supplied accumulator | One mutable result | Readable aggregation |
group_by |
Hash of arrays | Retains all grouped elements | Built-in grouping |
Microbenchmarks are most useful when they preserve the shape of production data. This benchmark creates the same hash with two methods:
require "benchmark/ips"
rows = 100_000.times.map { |i| { id: i, value: i % 10 } }
Benchmark.ips do |x|
x.config(time: 5, warmup: 2)
x.report("each_with_object") do
rows.each_with_object({}) do |row, index|
index[row[:id]] = row
end
end
x.report("reduce") do
rows.reduce({}) do |index, row|
index[row[:id]] = row
index
end
end
x.compare!
end
Run it on the Ruby version used in deployment and inspect the comparison rather than trusting a single number. Hash reallocation, garbage collection pauses, and CPU contention can change the ranking. For a service running continuously, total allocations and pause behaviour may matter more than a small difference in a five-second sample.
Bound memory with batching and streaming
The accumulator reduces intermediate collections, not the size of the final result. If every row is retained in a hash or grouped array, memory still grows with the input. It also keeps the same object references rather than copying records, so treat accumulation as a deliberate retention decision.
index = {}
rows.each_slice(500) do |batch|
batch.each_with_object(index) do |row, memo|
memo[row[:id]] = row
end
end
This version processes a bounded slice at a time while sharing one index. If the goal is only counts or sums, aggregate each slice and merge small summaries instead of keeping source records. That changes the algorithm from retaining every object to retaining only the information required by the report.
Use each_slice for an existing array. For an ActiveRecord::Relation, find_each or find_in_batches yields records in batches and avoids loading the whole table. Avoid converting a relation to an array first, because that removes the memory benefit before processing begins. The same principle applies to custom enumerators that can be made lazy.
Protect correctness in production workloads
Correctness tests should cover duplicate identifiers, missing keys, empty inputs, and frozen objects. Benchmarks should use those same edge cases: a happy-path data set often hides the extra arrays or repeated lookups that appear under pressure. The TYPO3 unit-test example illustrates a useful habit from another stack by defining representative data clearly and exercising expected behaviour repeatedly.
For Australian SaaS and retail workloads, logs and test payloads may contain names, addresses, or customer identifiers covered by the Privacy Act 1988 and the Australian Privacy Principles. Minimise copied fields, avoid printing raw records during benchmarks, and replace identifying values with synthetic fixtures where the business logic permits. This keeps optimisation work aligned with local privacy obligations and reduces both disclosure risk and memory overhead.
Shared monitoring should also identify the relevant Australian time zones and daylight-saving offsets. Sydney and Melbourne may appear identical for much of the year, while Brisbane remains on a different seasonal clock. Stable batch windows and accurately labelled runs produce more useful comparisons than measurements started at slightly different local hours.
Recommendations for large Ruby collections
These recommendations keep the change small enough to verify and large enough to matter:
- Choose the output shape first. Confirm whether duplicate identifiers should overwrite, coexist, or raise before writing the accumulation block.
- Benchmark representative rows with
Benchmark.ips, and inspect allocations as well as elapsed time on the deployed Ruby version. - Chunk or stream whenever the accumulator retains source objects; aggregate counts and sums instead of materialising every record.
- Keep each block focused on the accumulator, and avoid temporary arrays, repeated lookups, and needless collection conversions.
- Exercise empty collections, missing fields, duplicates, and frozen inputs with synthetic data that contains no customer identifiers.
Run one real batch through the revised code today, save the benchmark and its output, then publish the reproducible lesson through The Coding Journal.
cat ~/interests.json
| Key | Value |
|---|---|
| editor | Terminal-first workflow |
| os | Mac OS X / Unix |
| vcs | Git, distributed version control |
| deploy | Capistrano, cron automation |
| graphics | SVG, Adobe Illustrator troubleshooting |
| networking | IP validation, SSH, VPN |
git log --oneline --reverse
Solving SVG import issues in Adobe Illustrator CS6 and CC
When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.
Solving NDK build issues on OS X
Troubleshooting native development kit compilation problems on Mac OS X.
Programmatically adding PHP generated TypoScript to the backend configuration
Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.
ArgumentError: Could not parse PKey: no start line
Debugging an SSH key parsing error encountered during deployment.
Validating IP-Addresses in PHP
Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.
Cocoa: Using NSTrackingArea
A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.
cat ~/contact.txt