5

While browsing the ruby documentation, I found the replace method, but I cannot figure out what can be the use case of this method.

The only thing I can think of is about memory management (something like no reallocation needed if the new string has a length less or equal to the previous).

Any ideas ?

0

2 Answers 2

3

The use case is really just if you want to achieve something much like pass-by-reference in other languages, where a variable's value can be changed directly. So you could pass a String to a method and that method may entirely change the string to something else.

You could achieve the same thing in a more round-a-bout way, however, by emptying the String and appending some new string to the empty string. Other classes have similar methods (see Array and Hash).

If you find yourself really feeling the need to use these methods, however, chances are, you have backed yourself into a corner and should be seeking another way out than one which requires mutating an entire string (e.g. pass a data structure into a method, instead of just a string).

1
2

An entire string, as opposed to a substring, may be replaced using the replace method:

myString = "Welcome to PHP!"

=> "Welcome to PHP!"

myString.replace "Goodbye to PHP!"

=> "Goodbye to PHP!"

Source - http://www.techotopia.com/index.php/Ruby_String_Replacement,_Substitution_and_Insertion#Changing_a_Section_of_a_String

3
  • Yep, but what's the point of doing that ? myString = "Hello" followed by myString = "world" does the same (except maybe for memory management ?)
    – Scharron
    May 29, 2012 at 13:22
  • 1
    @Scharron: No, it doesn't even remotely do the same. String#replace replaces the contents of the string object. What you are doing is assigning a completely different, totally unrelated string to the same variable. May 29, 2012 at 18:33
  • @JörgWMittag: Yup, I finally understood (see the accepted answer).
    – Scharron
    May 29, 2012 at 18:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.