paint-brush
NamedStruct — Improving Ruby’s Structby@RohitPaulK
114 reads

NamedStruct — Improving Ruby’s Struct

by Paul KuruvillaOctober 8th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This post describes what I think is a major flaw in Ruby’s built-in <a href="https://ruby-doc.org/core-2.4.2/Struct.html" target="_blank">Struct</a> class, and proposes a workaround.
featured image - NamedStruct — Improving Ruby’s Struct
Paul Kuruvilla HackerNoon profile picture

This post describes what I think is a major flaw in Ruby’s built-in Struct class, and proposes a workaround.

Documentation for Ruby’s built-in Struct class

This blog post does a good job of explaining the benefits of using Struct for value objects.

Here’s my gripe with Struct: Although fields in a Struct are named (unlike an array, or Python’s tuple), named/keyword arguments aren’t allowed when instantiating a Struct object.

This defeats the purpose of having named fields in the first place! The benefit of having named fields is that they attach meaning to your data. Birthday.new(day: 5, month: 7) is undoubtedly more clear than Birthday.new(5, 7).

To work around this, I’ve been adding the following class to all projects where I use Struct:

This is also available as a gem, if you’d prefer to not repeat yourself.