Struct
Sometimes you want to create a small object to hold data that has little to no behavior of its own, and a Ruby class seems like too much structure to bother with.
Ruby has a few lightweight ways to create classes that have little to no behavior.
The most commonly used is probably Struct. You can use Struct to create instance-like objects that have attributes and can respond to messages that you define.
Using Struct creates a class that you then create instances of. Let’s say you want to represent a classroom that has a name and a capacity. You use Struct.new to create a Classroom class, with the desired attribute names as arguments. You can then use Classroom.new to create new classrooms. The positional arguments in new match the order ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access