Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Create Struct with Keyword Args in Ruby

I use Ruby Structs all the time. They’re great… if you don’t, check them out!

However I have found them a bit cumbersome to set up because they are generally used with positional arguments:

Money = Struct.new(:price, :currency)
Money.new(1.23, "USD")

Be cumbered no more! I have found a different approach.

Money = Struct.new(:price, :currency, keyword_init: true)
Money.new(currency: "USD", price: 1.23)

Using the keyword_init argument allows the new Struct instantiation to accept keyword arguments which, I find, clearer to read and also do not need to be positional.

Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.