Today I Learned

A Hashrocket project

Create Named Structs With

I often see Struct used to create some one-off anonymous data structure like so:

> person =, :age)
=> #<Class:0x007fc6c89112e8>
>"Alice", 33)
=> #<struct name="Alice", age=33>

This will often get the job done, but on its own the resulting data structure doesn’t tell us as much as it could.

We can say more with a named struct:"Person", :name, :age)
=> Struct::Person
>"Bob", 24)
=> #<struct Struct::Person name="Bob", age=24>

When the first argument is a string that can be converted to a constant, then we’ll get a named struct that is subclassed under Struct.

We can also assign the struct initialization to a constant to do a similar thing:

> Person =, :age)
=> Person
>"Jerry", 45)
=> #<struct Person name="Jerry", age=45>


Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. Contact us and find out how we can help you.