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 ?
String is used to tie, bind, or hang other objects. It is also used as a material to make things, such as textiles, and in arts and crafts. String is a simple tool, and its use by humans is known to have been developed tens of thousands of years ago.
Strings are called "strings" because they are made up of a sequence, or string, of characters.
Most programming languages have a data type called a string, which is used for data values that are made up of ordered sequences of characters, such as "hello world". A string can contain any sequence of characters, visible or invisible, and characters may be repeated.
A string is any series of characters that are interpreted literally by a script. For example, "hello world" and "LKJH019283" are both examples of strings.
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).
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
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