Using Ruby Structs To Subclass

December 10, 2012

A struct is Ruby’s convenient way of letting you bundle a bunch of attributes together (complete with accessor methods) without having to define a specific class.

For example I could have:

Employee = Struct.new(:name,:id,:company)
puts "Employee is a class?: "+Employee.is_a?(Class).to_s # =>true
josh = Employee.new("josh",1,"Google")
puts "Josh is an Employee? "+josh.is_a?(Employee).to_s # =>true

With the above, I have defined an Employee class of which josh is an instance.

Subclassing with Struct

In computer science lingo, a subclass is a class that inherits data and properties from another class. Since a Struct is a class in Ruby, we can subclass on it.

But why would we want to do this?

One interesting use case I found is to use it to shorten up class definitions. For instance, here is how you would normally define a class:

Example #1 OriginalCircle Class (normal class definition)

class OriginalCircle
attr_accessor :radius
  def initialize(r)
    @radius = r
  end

  def diameter
    2*@radius
  end

  def circle_area
    Math::PI*@radius*@radius
  end
end

And here is how you would do it using Ruby’s Struct:

Example #2 Circle Class (subclassing with struct)

class Circle < Struct.new(:radius)
  def diameter
    2*radius
  end

  def circle_area
    Math::PI*radius\*radius
  end
end

Notice that by subclassing with a struct (example 2), the “initialize” method is given to you “automagically.”

You also get the accessor method free of charge

So you can do:

c=Circle.new(1)
c.radius = 2

This changes the radius from 1 to 2. Notice I didn’t have to declare “attr_accessor” like I did in example 1.

I think this is pretty nifty. What other nifty or interesting things have you found with Struct? Feel free to share in the comments below.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.