Admit it: you like the unusual. We all do. Despite constant warnings against premature optimization, an emphasis on "readable code", and the old aphorism, "keep it simple, stupid", we just can't help ourselves. As programmers, we love exploring new things.
In that spirit, let's go on an adventure. In this post, we'll take a look at seven lesser-known ways to store data in the Ruby language.
The Ones We Already Know
Before we get started, we'll set a baseline. What are the ways to store data in Ruby that we use every day? Well, these are the ones that come to mind for me: string, array, hash, CSV, JSON, and the filesystem.
We can skip all of these.
So what are some of the other ways to store data in Ruby? Let's find out.
What Is It?
A struct is a way of bundling together a group of variables under a single name. If you've done any C programming, you've probably come across structs before.
A struct is similar to a class. At its most basic, it's a group of bundled attributes with accessor methods. You can also define methods that instances of the struct will respond to.
In Ruby, structs inherit from Enumerable, so they come with all kinds of great behavior, like
map, and member access with
You can define a struct object by setting a constant equal to
Struct.new and passing in some default attribute names. From there, you can create any number of instances of the struct, passing in attribute values for that instance.