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

Values

> 编程语言
开源

适用于 Ruby 的简单不可变值对象 (Readme 文件比代码长)

546 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

适用于 Ruby 的简单不可变值对象 (Readme 文件比代码长)

Values

Summary

Values is a tiny library for creating value objects in ruby.

Classes created using Value mostly look like classes created using Struct or OpenStruct, but fix two problems with those:

Problems with Struct and OpenStruct

Struct and OpenStruct constructors can take fewer than the default number of arguments and set other fields as nil:

ruby
Point = Struct.new(:x, :y)
Point.new(1)
# => #
ruby
p = OpenStruct.new(x: 1)
# => #
p.y
# => nil

Struct and OpenStruct objects are mutable:

ruby
p = Point.new(1, 2)
p.x = 2
p.x
# => 2
ruby
p = OpenStruct.new(x: 1, y: 2)
p.x = 2
p.x
# => 2

Values is Better

Values fixes both of the above problems.

Constructors require expected arguments:

ruby
Point = Value.new(:x, :y)
Point.new(1)
# => ArgumentError: wrong number of arguments, 1 for 2
# from /Users/tcrayford/Projects/ruby/values/lib/values.rb:7:in `block (2 levels) in new
# from (irb):5:in new
# from (irb):5
# from /usr/local/bin/irb:12:in `

Instances are immutable:

ruby
p = Point.new(1, 2)
p.x = 1
# => NoMethodError: undefined method x= for #
# from (irb):6
# from /usr/local/bin/irb:12:in 

Features

Values also provides an alternative constructor which takes a hash:

ruby
p = Point.with(x: 3, y: 4)
p.x
# => 3

Values can copy and replace fields using a hash:

ruby
p = Point.with(x: 1, y: -1)
q = p.with(y: 2)
# => #

Value classes can be converted to a hash, like OpenStruct:

ruby
Point.with(x: 1, y: -1).to_h
# => {:x=>1, :y=>-1}

Values also supports customization of value classes inheriting from Value.new:

ruby
class Point  ""

Values does NOT have all the features of Struct or OpenStruct (nor is it meant to).

Issues· 0 开放

查看全部 Issues在 GitHub 打开

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

> 标签

Ruby

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

> 工具信息

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

> 相关工具

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