Ruby 2.5 was released a few days ago. Among the new features,
Structs gained the ability to be instantiated with using keyword arguments.
Ruby has traditionally had the ability to create a classes that bundle data attributes together, provide accessors for those attributes and other methods like converting into a hash:
1 2 3 4 5
Notice, that the newly created class is initialized with positional arguments. Often when using Ruby – especially when using Rails, data is passed around in hashes. For example, let’s assume that we are instantiating an instance of a
Point inside a controller action using Rails. The instantiation would look something similar to:
As the number of positional arguments grow, this can become tedious. Ruby 2.5 ships with a new feature that allows creating
Structs that accept keyword arguments, much like
ActiveRecord models do, as described in this feature request.
1 2 3
There are a few things to note. When using keyword arguments, if a value is missing, it will be set to
nil. Additionally, if extra arguments are supplied, an
ArgumentError will be raised:
1 2 3
Stuck in an older ruby? You can easily build similar support on your own, which I often do in projects I work on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
We’ve created a new module that takes advantage of the
#members method in
Struct to define a dynamic initializer. Note that in this version, extra arguments will not raise an
ArgumentError. Depending on your application, this might be a better fit or not. It’s left to the reader to make a version that does raise an error with extra arguments.