May 21 2007

Ruby Struct

A Struct in Ruby is a convenient and elegant way to bundle attributes together without having to write a class with explicit accessor methods.

For example, let's look at a DTO used with a Rails ActionMailer class:

class EmailDto <, :email, :date); end

So in a Model we can have something along the lines of:

class Account < ActiveRecord::Base
  def activate = true;
    dto =,,

... with a Notifier that looks like:

class Notifier < ActionMailer::Base
  def activation_notification(dto)
    @recipients =
    @from = ""
    @subject = "Your account is now active!"
    @body[:content] = dto

An interesting, more flexible/dynamic alternative to Struct is OpenStruct. OpenStruct allows the creation of data objects which accept arbitrary attributes at any time.

require 'ostruct'

flexie = => 'rock')
flexie.bands = ['zep', 'sabbath'] # => "rock"
flexie.bands.first # => "zep"

Of course, attributes can always be assigned blocks:

flexie.hello = { puts 'hello world'} # => hello world

In many cases, Structs can offer a more meaningful, more concrete alternative to aspects of what Hashes are currently popular for in Ruby.