Two niceties about Ruby Structs
I recently discovered a couple of niceties about Ruby Structs that made me love them even more.
Constructor with keyword arguments
Since version 2.5 you can create structs with keyword arguments by passing
Person= Struct.new(:name, :email, keyword_init: true) Person.new(name: 'Jorge', email: 'firstname.lastname@example.org')
It doesn’t look like a big deal, but it made me use
Struct much more often. Before, your only option was passing the list of positional arguments when constructing them. This is not ideal when having more than two or three properties. Code gets difficult to read, and you are forced to pass a value for every property. The new approach reads nicely, and it makes every argument optional.
Support for hash and compare
Struct provides an implementation of
hash methods based on its attributes. This is a sensible approach that works well in most cases and saves you a lot of boilerplate code for things like dealing with equality in tests, or for dealing with Hash or
Recently I have been working in a project that involves dealing with a rich domain, and I’ve found myself using structs as the starting point for many domain classes. Learning about
keyword_init was a game changer for me and realizing I was getting sensible implementations for hash and equality methods for free only added to my desire of using them.