Proper way to use the Struct
04 Oct 2015
We use Structs in Ruby to create simple classes with constructor and some instance variables.
Look at this simple
Using Struct, you can simply use a single line instead of declaring
attr_accessors and constructor and the class will have exactly the same API:
But when it comes to a class with internal resources like constants, you may get a warning:
What happends here? We assumed that
MIN_AGE was declared inside
Admin, but actually it was declared on the top level:
And warnings were printed.
But wait, there is actually a proper way to subclass from Struct:
No warnings here!
I also recommend you to check it the post by Steve Klabnik, where he describes all power of Struct.