4

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.

2
  • 4
    It sounds like you don't want to make the String immutable, but rather to restrict the ability to mutate it. Commented Jun 21, 2012 at 23:49
  • @zetetic: Agree. Thats precisely what I want. Commented Jun 21, 2012 at 23:56

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using dup sounds perfect to me. I wouldn't want to modify the base String class because it will probably buy trouble for later debugging.
Thanks. String#dup is a nice fit for the above scenario.
2

Call #freeze on the String. See: http://ruby-doc.org/core-1.9.3/Object.html#method-i-freeze

2 Comments

Thanks, but this won't work in my case. Please see the edit to my original post.
+1 to this answer because it is always possible to #dup frozen string and the result would be a mutable copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.