Ruby equivalent of Java's Collections.unmodifiableList and Collections.unmodifiableMap

193 views Asked by At

Is there a equivalent in the Ruby standard API for Java's Collections.unmodifiableList and Collections.unmodifiableMap?

2

There are 2 answers

0
Uri Agassi On BEST ANSWER

Use freeze API:

Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.

This method returns 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.

0
Dmitry Ginzburg On

If you want to create, for example, unmodifiable (immutable) list:

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