Is there a equivalent in the Ruby standard API for Java's Collections.unmodifiableList
and Collections.unmodifiableMap
?
Asked
Active
Viewed 189 times
5
-
You probably should tag ruby first, and explain what those do. – Anubian Noob May 26 '14 at 20:14
-
1You may use `freeze` method. See http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html – Dmitry Ginzburg May 26 '14 at 20:20
2 Answers
7
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.

Uri Agassi
- 36,848
- 14
- 76
- 93
2
If you want to create, for example, unmodifiable (immutable) list:
a = [ "a", "b", "c" ]
a.freeze

Dmitry Ginzburg
- 7,391
- 2
- 37
- 48