Enums or Whose String is it Anyway?

Morgan Collado
2 min readApr 13, 2021

One of the challenges that a junior developer faces is the problem of you don’t know what you don’t know. Case in point, I was meeting with my mentor this week, looking over a project that I had built and she asked me “Why didn’t you write this attribute as an Enum?”

To which I reply, “I don’t know her.”

Mariah Carey shaking her head and saying, with a smile, “I don’t know her”

Unlike Mariah, I do want to get to know her!

So, what are enums? Enums are a layer of abstraction given to us by ActiveRecord in Rails. It allows us to create a integer column on our model. Then, within the model, you can write the following code to map those integers to the whatever symbol you need within your code to be expressive.

enum status: [:not_started, :initial_pickup, :clinic_dropoff, :clinic_pickup, :final_dropoff]

In the above example, I have a column in my Rides model with a name of Status that is the data type of integer. The above code allows me to map the integer 0 to mean `:not_started`. So whenever I set the model’s attribute of status to :not_started, the database knows to save this data as the number 0. This is much more performant then using strings because the database doesn’t actually care about how we store the data. Using enum allows us to abstract these strings into integers which takes up less memory then the full string.

This allows us to control the attribute so that a user cannot input a string that is not anticipated and keeps our database fast.

You may be wondering where the Whose Line is it Anyway? reference is but much like the show, the blog is made up and title doesn’t matter.

--

--

Morgan Collado

Morgan is a software developer working at the intersections of gender, race and class.