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 ?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Scharron
  • 17,233
  • 6
  • 44
  • 63

2 Answers2

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

d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • This link is useful to understand why such a method is useful : http://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value – Scharron May 29 '12 at 13:35
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

Miguel Ping
  • 18,082
  • 23
  • 88
  • 136
Prateek Kiran
  • 35
  • 1
  • 7
  • 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 '12 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. – Jörg W Mittag May 29 '12 at 18:33
  • @JörgWMittag: Yup, I finally understood (see the accepted answer). – Scharron May 29 '12 at 18:36