Ruby Patterns: Mass Assignment

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

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 common pattern in programming is to instantiate a new object and assign a bunch of attributes during initialize. You probably recognize code like this:

Blog post image: tumblr_mevwx9EIow1rtan47.png

While this works, it’s redundant and tedious. You also have to keep track of what order the parameters have to be in when creating the object. Wouldn’t it be nice if we could pass in any number of attributes to be assigned and specify which attributes they should be assigned to without having to write a ton of code?

It turns out that we can. Ruby makes it particularly easy with some metaprogramming magic and the .send method:

Blog post image: tumblr_mevwxh9GeK1rtan47.png

This is mass assignment: a pattern that is extremely common and implemented in a ton of Ruby libraries, including ActiveRecord. It allows us to initialize objects with a hash, where the key corresponds with the attribute we are setting and the values represent the attribute values. It’s more flexible, more fun, and less code.

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat