Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 872
razenha Avatar asked May 26 '14 20:05

razenha


People also ask

What is Unmodifiable collection?

Collections that do not support modification operations (such as add , remove and clear ) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable. Collections that additionally guarantee that no change in the Collection object will be visible are referred to as immutable.

How do you make an unmodifiable collection?

Collectors class has Collectors that create new unmodifiable collections from the elements of the streams. For example, to transform the elements of a source collection and place the results into an unmodifiable set, you can do the following: Copy Set<Item> unmodifiableSet = sourceCollection.

Is Unmodifiable list immutable?

A collection is considered unmodifiable if elements cannot be added, removed, or replaced. However, an unmodifiable collection is only immutable if the elements contained in the collection are immutable.

How to return unmodifiable map in Java?

The unmodifiableMap() method of java. util. Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with “read-only” access to internal maps.


1 Answers

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.

like image 127
Uri Agassi Avatar answered Nov 03 '22 21:11

Uri Agassi