Last Updated: February 25, 2016
·
4.886K
· ianrgz

Inheriting from: Struct

In this quick tip we're going to learn how to initialize a class using a Struct object rather than the conventional way.

In ruby, whenever a class is instantiated the ruby interpreter calls the initialize method automatically if there is any, take for example the following class:

class Car
  def initialize(brand, model)
    @brand = brand
    @model = model
  end
end

Now let's take a quick look at the Struct class in ruby, a Struct provides us with a way to bundle data together without having to define a class, once you assign an instance of a Struct to constant it behaves pretty much like a class, take the following example:

Car = Struct.new(:brand, :model)
car = Car.new('My Brand', 'my_model')

There is however a way to use the best of both constructs, the way we do it is by subclassing our classes from a Struct object like so:

class  Car < Struct.new(:brand, :model)
  ...your super awesome code goes here
end

This way we can get rid of the initialize method and our class will pretty much behave like it should, and another convenience of this is that the Struct will provide us with accessor methods to access our class' attributes, so our final class will look like this:

class Car < Struct.new(:brand, :model)
  #example method
  def car_brand_and_model
    "My car is a: #{brand} #{model}"
  end
end

And this is about it on improving our class' constructor by inheriting from a Struct object, hope you find it useful.

2 Responses
Add your response

It's useful to know that you can customize a Struct with a block as well. This code has the same effect as your example where you inherit from Struct, and it doesn't create an extra, unnamed class to inherit from.

Car = Struct.new(:brand, :model) do
  def car_brand_and_model
    "My car is a: #{brand} #{model}
  end
end

Just thought I'd point it out for completeness…

over 1 year ago ·

Many years after :P

But thanks a lot for your comment martinsvalin

over 1 year ago ·