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:
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:
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.