SHARE:
Uncategorized

Ruby Structs

Flatiron School / 20 November 2012

The following is a guest post by Kevin Curtin and originally appeared on his blog. Kevin is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

A Struct is a convenient way to store data and bundle attributes together. These slides on Speaker Deck do a great job of describing what a Struct is, how to use them, and why they are awesome.

Here is an example:

Let’s say we want to store Birthdays.

While each of the above implementations does what we want them to do (they store birthdays), there are issues with each of them:

  1. The array will store the values you need, but doesn’t give you any information about what the values represent and it’s difficult to keep track of.
  2. The hash gives you information about what the values represent, but is difficult to access and manage.
  3. The Date is the best, it tells you what the values represent. But it still doesn’t give you information about what the Date itself represents.

My solution is to store this data in a Struct:

I like this approach because using a Struct gives you alot more context about the object that you’re looking at. You know that it’s a date and you know that the date represents a birthdaybecause it explicitly tells you. Being explicit about what values represent and providing context is never a bad thing.

Check out the slides from the presentation I mentioned above to learn more about iterating over Structs and some of the additional functionality you get by using them.

BONUS: Check out these alternative syntaxes for creating Structs and take a look at the official documentation:

How Params Works in Rails Previous Post How to Query NYC Open Datasets With Socrata Next Post