I was recently introduced to OpenStruct in Ruby and how it can create objects via metaprogramming. It does this by creating a method defined by hash key’s and sets the value’s to the value’s. This is similar to mass assignment with keywords in Ruby. Let’s take an example
This creates a new object OpenStruct object student
that now has the methods #name, #age, and #major methods available to it instead of throwing undefined method errors.
OpenStruct can add whatever object we want by just defining it like so
As the ruby-docs mentions, OpenStruct can get a bit costly in performance. A cheaper way and more restricted way to create objects can be achieved with Struct. #### New Objects with Struct Struct objects need to have their methods defined before hand, unlike OpenStruct.
If you look at the output for when we defined Professor = Struct.new(:name, :age)
we are actually defining a new rubly class object! You can confirm this by running Professor.class
and it will return Class
. However, Struct are not able to define new methods (attrs) on the fly
So here we have a couple of different ways to create ruby objects with attributes. However, I’m still not sure when we’d need to actually use such techniques. Perhaps when making really simple classes but I think I’d rather define my classes with mass assignment with keywords, like in this lesson from the Flatiron School.