ruby notes

Small things I keep relearning about Ruby.

Living with frozen string literals

Adding # frozen_string_literal: true to the top of a file makes every string literal in it immutable. On a fresh project it is invisible. On an old one, the first run usually ends with a FrozenError somewhere deep in a helper that builds output with <<.

Almost every failure I hit came from the same shape of code:

buf = ""
items.each { |i| buf << i.to_s << "\n" }

The fix is to ask for a mutable string explicitly:

buf = +""
# or
buf = String.new(capacity: 1024)

Unary plus returns the receiver if it is already mutable, or a duplicate if it is frozen. String.new also lets you preallocate, which is nice for large buffers.

The other surprise was gems that mutate strings you pass in. Those need a dup at the call site, and are worth reporting upstream.