Create struct-like classes that don't have setters, but have an awesome constructor.
Latest commit 94f44ac Sep 2, 2016 @davetron5000 davetron5000 committed on GitHub Merge pull request #21 from stitchfix/gem-update-2016-09
bundle update



Build Status

Creates struct-like classes (that can build value objects) that do not have setters and also have better constructors than Ruby's built-in Struct.

This is highly useful for creating presenters, non-database-related models, or other quick and dirty classes in your application. Instead of using a Hash or OpenStruct, you can create a bit more clarity around your types by using ImmutableStruct, which is almost as convienient.


Add to your Gemfile:

gem 'immutable-struct'

Then install:

bundle install

If not using bundler, just use RubyGems:

gem install immutable-struct

To use

Person =, :age, :job, :active?, [:addresses]) do
  def minor?
    age < 18

p = "Dave",   # name will be 'Dave'
               age: 40,        # age will be 40
                               # job is omitted, so will be nil
               active: true)   # active and active? will be true
                               # addresses is omitted, but since we've selected
                               # Array coercion, it'll be []      # => "Dave"
p.age       # => 40   # => true
p.minor?    # => false
p.addresses # => []

p2 = "Dave", age: 40, active: true)

p == p2     # => true
p.eql?(p2)  # => true

SimilarPerson =, :age, :job, :active?, [:addresses])

sp = "Dave", age: 40, active: true)

p == sp     # => false         # Different class leads to inequality

new_person = p.merge(name: "Other Dave", age: 41) # returns a new object with merged attributes    # => "Other Dave"
new_person.age     # => 41 # => true

You can also treat the interior as a normal class definition.