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.