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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With