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

raz*_*nha 5 ruby java collections unmodifiable

是否有适用于Java的Ruby标准API Collections.unmodifiableListCollections.unmodifiableMap

Uri*_*ssi 7

使用freezeAPI:

防止进一步修改obj.如果尝试修改,将引发RuntimeError.无法解冻冻结的物体.另见Object#frozen?.

此方法返回self.

a = [ "a", "b", "c" ]
a.freeze
a << "z"
Run Code Online (Sandbox Code Playgroud)

生产:

prog.rb:3:in `<<': can't modify frozen array (RuntimeError)
 from prog.rb:3
Run Code Online (Sandbox Code Playgroud)

您还可以将hamster gem用于其他不可变数据结构.