Ruby 2.7.0 preview 2 已经发布了,最终版本计划在 12 月发布。该版本引入了一些新特性和性能改进,主要是:
- Compaction GC
- Pattern Matching
- REPL improvement
- Separation of positional and keyword arguments
Compaction GC
这个版本引入了 Compaction GC,以碎片化内存空间。GC.Compact 方法对堆进行压缩,这个函数压缩堆中的活动对象,以使用更少的页,并且堆会更友好。
Pattern Matching(实验性)
模式匹配是函数式程序设计语言中广泛使用的一种特性。通过模式匹配,可以遍历给定的对象并分配其值。
case JSON.parse('{...}', symbolize_names: true)
in {name: "Alice", children: [{name: "Bob", age: age}]}
p age
...
end
REPL improvement
irb 现在支持多行编辑,它由 reline,readline 兼容的纯 Ruby 实现驱动。它还提供 rdoc 集成。在 irb 中,可以显示给定类、模块或方法的引用。
Separation of positional and keyword arguments
关键字参数和位置参数的自动转换,将在 Ruby 3 中将删除。
其他显著新特点:
- 引入编号参数作为默认块参数
- 添加 Enumerable#tally
["a", "b", "c", "b"].tally
#=> {"a"=>1, "b"=>2, "c"=>1}
- 现在允许在 Self 上调用私有方法
def foo
end
private :foo
self.foo
- 添加 Enumerator::Lazy#eager
a = %w(foo bar baz)
e = a.lazy.map {|x| x.upcase }.map {|x| x + "!" }.eager
p e.class #=> Enumerator
p e.map {|x| x + "?" } #=> ["FOO!?", "BAR!?", "BAZ!?"]
另外,还有更新部分标准库:
- Bundler 2.1.0.pre.1
- RubyGems 3.1.0.pre.1
- CSV 3.1.2 (NEWS)
- Racc 1.4.15
- REXML 3.2.3 (NEWS)
- RSS 0.2.8 (NEWS)
- StringScanner 1.0.3
更多详情见发布说明。