Don’t Inherit From Struct

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.