Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Ruby string immutable

Tags:

string

ruby

Need to make certain Ruby strings in my program to be immutable. What is the best solution? Writing a wrapper over String class?

The freeze method won't work for me. I see that freeze won't allow you to unfreeze the object.

Following is my situation: I have a class that passes a string to a callback. This string happens to be an instance variable of the class and can be potentially large. I don't want the callback to modify it, but still allow the class to modify it at will.

like image 755
Kowshik Avatar asked Dec 16 '22 22:12

Kowshik


1 Answers

Following is my situation: I have a class that passes a string to a callback.

Would passing a copy of the string to the callback work?

This string happens to be an instance variable of the class and can be potentially large. I don't want the callback to modify it, but still allow the class to modify it at will.

If you're worried about the size of the string, then using String#dup will help. It'll create a new object, with a distinct object_id, but the contents of the string won't be copied, unless the new string (or the original) gets modified. This is called "copy on write", and is described in Seeing double: how Ruby shares string values.

like image 92
Andrew Grimm Avatar answered Dec 28 '22 23:12

Andrew Grimm