Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
I

immutable-struct

> 编程语言
Open source

Create struct-like classes that don't have setters, but have an awesome constructor.

171 stars0 likes1 views
WebsiteGitHub

About

Create struct-like classes that don't have setters, but have an awesome constructor.

ImmutableStruct

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 convenient.

Install

Add to your Gemfile:

ruby
gem 'immutable-struct'

Then install:

bundle install

If not using bundler, just use RubyGems:

gem install immutable-struct

Usage

…

You can coerce values into struct types by using the from method. This is similar to Ruby's conversion functions, e.g. Integer("1").

ruby
dave = Person.from(p)
dave.equal?(p) # => true (object equality)

daveish = Person.from(dave.to_h)
daveish.equal?(dave) # => false
daveish == dave      # => true

You can treat the interior of the block as a normal class definition with the exception of setting constants. Use const_set to scope constants as-expected.

ruby
Point = ImmutableStruct.new(:x, :y) do
  const_set(:ZERO, 0)
  ONE_HUNDRED = 100
end
Point::ZERO   # => 0
::ONE_HUNDRED # => 100
::ZERO        # => NameError: uninitialized constant ZERO

Links

  • rdoc
  • source
  • blog

Issues· 3 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言