Current Favorites in Ruby: Structs, .nil?, and Retries
November 10, 2014
I've said it before, but I'll say it again: I love Ruby! Here are some of my favorite Ruby features these days.
Struct is a quick way to create simple classes with a set of readable and writeable attributes.
Interacting with structures is exactly like interacting with the equivalent classes. They can be instantiated with any number of parameter arguments up to the number of attributes in
Struct.new, with the nth parameter being assigned to the nth attribute. Any attributes not set during instantiation are nil.
To make your structures do more than just store a set of attributes, you can pass them a block:
I've mostly used Structs for nested helper classes that support larger data structures, like entry structures in dictionaries or linked node structures in trees.
.nil? is easy to take for granted, but it is a great example of the amazing simplicity in the Ruby language. In many other languages, some things are objects while other things are primitives. In Ruby, everything is an object - numbers, strings, and even nil itself. This means that with Ruby, you can test values like this:
The Workings of this Magic
Object class, which all other classes inherit from, defines .nil? to return false.
NilClass is the one class that overrides .nil? to return true.
At work, I spend much of my time on a Rails application that communicates with various 3rd party services. Because mysteries happen,
retry has become my friend. A
retry inside of a
rescue block causes re-execution of the contents in the
This makes it easy in incorporate smart retry logic and failure alerts.
My inbox and my workplace's chat client thank
For more, see Ruby-Doc
Ruby is so pleasantly documented that I have read much of its documentation for fun. Luckily, there's still an unending number of subtle, powerful features that I have yet to learn about, so I won't get bored for a while. Check out the documentation here!