Code Worth Reading
How Ruby made me appreciate code readability
A.I. agents write more of our code every month, and when they reach for a scripting language, they reach for Python. Fewer and fewer people read what comes back. The tests pass, the diff gets a glance, and it ships.
I fear for Ruby in that world. Its best quality is what it is like to read, and that quality only counts when someone reads.
So this is a post about Ruby, and about code as something that can be beautiful. I think it can, and I think beautiful code makes happier programmers.
Reading is the job
Code gets read far more often than it gets written. With an agent at the keyboard, reading becomes most of the job: we review, we debug, we decide what stays.
That makes the language the agent writes in matter more.
Code that says what it does
return if items.empty?
users.select(&:admin?).map(&:email).sort
empty? asks a question, select(&:admin?) keeps the admins, and the chain reads left to right in the order things happen. Someone who has never written Ruby can tell what it returns.
One idea, small code
File.open("log.txt") do |f|
f.each_line { |line| puts line if line.include?("ERROR") }
end
A block is a chunk of code handed to a method. Iteration, cleanup and configuration all use it, and File.open closes the file when the block ends.
Few concepts keep the code small, and small code fits in your head.
Code in the words of its domain
describe Cart do
it "sums its items" do
expect(cart.total).to eq(42)
end
end
RSpec is plain Ruby: methods, blocks and a little metaprogramming. Ruby lets a library speak the language of its subject, so a test reads like the sentence that describes it.
Code shaped like the data
case response
in { status: 200, body: }
render body
in { status: 404 }
not_found
end
Pattern matching became a full part of the language in Ruby 3.0. You write the shape of the data you expect, and Ruby pulls out the parts you named.
Thirty years in, the language still grows toward code that reads well.
Happier programmers
Matz designed Ruby to make programmers happy. Code you enjoy reading is code you come back to, fix and improve. Code you dread gets worked around.
Beautiful code is code someone wants to read, and that is worth keeping when an agent does the writing.
Next time an agent hands you a script, read it, and ask whether you would enjoy reading it again.