Lessons from WriteBook - Lesson 1 - Eloquent Ruby Snippets
The best way of learning is by reading and extracting.
Here is a lesson from 37 Signal’s Writebook code base.
I’ve extracted it as a quiz for you:
# how would you convert this array:
color_array = ["black", "blue", "green", "magenta", "orange", "violet", "white"]
# into this hash:
color_hash = {"black"=>"black", "blue"=>"blue",
"green"=>"green", "magenta"=>"magenta",
"orange"=>"orange", "violet"=>"violet",
"white"=>"white"}
# and do so eloquently?
Answer:
%w[ black blue green magenta
orange violet white ].index_by(&:itself)
# => {"black"=>"black", "blue"=>"blue",
# "green"=>"green", "magenta"=>"magenta",
# "orange"=>"orange", "violet"=>"violet", "white"=>"white"}
Let’s break down the above:
- what does
%w
mean?? Results in an array of strings. - What does index_by mean? Basically it converts an enumerable into a hash.
itself
. I had never heard of that. But it is a ruby method which returns the object itself.
Shamelessly extracted from Basecamp’s Writebook, for your learning pleasure:
class Book < ApplicationRecord
# ...
enum :theme, %w[ black blue green magenta orange violet white ].index_by(&:itself), suffix: true, default: :blue
end
The only way of learning is by reading and implementing it yourself.
Permissions
I thank the creators of Basecamp for releasing Writebook!
I have extracted snippets purely for pedagogical purposes.
However, I have not sought permission to do this, and it is entirely possible that someone might object - if so, pls send me a msg and this post will be removed, no questions asked.
Written on May 12, 2025