简体   繁体   English

Ruby相当于Java的Collections.unmodifiableList和Collections.unmodifiableMap

[英]Ruby equivalent of Java's Collections.unmodifiableList and Collections.unmodifiableMap

Java的Collections.unmodifiableListCollections.unmodifiableMap的Ruby标准API中是否有等价物?

Use freeze API: 使用freeze API:

Prevents further modifications to obj. 防止进一步修改obj。 A RuntimeError will be raised if modification is attempted. 如果尝试修改,将引发RuntimeError。 There is no way to unfreeze a frozen object. 无法解冻冻结的物体。 See also Object#frozen?. 另见Object#frozen?。

This method returns self. 此方法返回self。

 a = [ "a", "b", "c" ] a.freeze a << "z" 

produces: 生产:

 prog.rb:3:in `<<': can't modify frozen array (RuntimeError) from prog.rb:3 

You can also use the hamster gem for other immutable data structures. 您还可以将hamster gem用于其他不可变数据结构。

If you want to create, for example, unmodifiable (immutable) list: 如果要创建,例如,不可修改(不可变)列表:

a = [ "a", "b", "c" ]
a.freeze

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM