Don't Inherit From Struct

December 13, 2012

I just finished looking through James Edward Gray II’s slides from his talk “10 Things You Didn’t Know Ruby Could Do”.

Number 64 caught my attention because I’ve been writing utility classes that inherit from Struct for years. (Ever since I first saw the pattern in DelayedJob’s README.)

For example, instead of this:

class Name < Struct.new(:first, :last)
  def full
    "#{first} #{last}"
  end
end

You should write this:

Name = Struct.new(:first, :last) do
  def full
    "#{first} #{last}"
  end
end

It’s not really a big deal, but the first example creates a class then immediately subclasses it. This needlessly leaves an extra class in the hierarchy. The second example simply assigns the created class directly to your new constant.

Discussion, links, and tweets

I'm a software developer focusing on Rails applications. Follow me on Twitter.