百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
I

immutable-struct

> 编程语言
开源

创建类似结构体的类,这些类没有设置器,但具有强大的构造器。

171 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

创建类似结构体的类,这些类没有设置器,但具有强大的构造器。

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 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

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