Upgrade Your Value Objects

In my previous article about value objects I talked about native Ruby options for creating and using value objects. Structs, OpenStructs, and Classes all have their own pros and cons when being used, but with the recent release of Ruby 2.5, Structs have gotten a small improvement that makes them usable in many more situations.

As of Ruby 2.5, Struct.new can create a Struct subclass that accepts keywords arguments on initialization. So you no longer need to be concerned about the order of the arguments, you can create objects the same way you would instantiate any class.

Being able to pass a hash to initialize a Struct is a pretty big benefit, and everything else about Structs is still the same. Getters and setters are pre-defined, you can define other functions, and you can compare objects.

As a bonus here are some other interesting/useful things about Structs that demonstrate how flexible they are:

1) You can access the members of a struct in several different ways.

2) You can call dig on them like a Hash or an Array

3) You can use other Enumerable/Hash/Array-ish methods

4) If you care about your value objects being immutable and complete when instantiated, you can do that yourself by overriding the initializer.

Play around with it a bit and see what else you can do. Hopefully, this gives you another tool in your toolbelt.

Eryan is a development director in DevMynd’s software engineering practice focusing on mobile apps and web development. He has been with the company since 2013.