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).

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

1 Comment

This link is useful to understand why such a method is useful : stackoverflow.com/questions/1872110/…
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 Comments

Yep, but what's the point of doing that ? myString = "Hello" followed by myString = "world" does the same (except maybe for memory management ?)
@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.
@JörgWMittag: Yup, I finally understood (see the accepted answer).

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.