Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a String#replace in Ruby?

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 ?

like image 946
Scharron Avatar asked May 29 '12 13:05

Scharron


People also ask

What is the point of a string?

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.

Why is it called a string?

Strings are called "strings" because they are made up of a sequence, or string, of characters.

What is called string?

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.

What is string example?

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.


2 Answers

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

like image 67
d11wtq Avatar answered Sep 28 '22 04:09

d11wtq


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

like image 28
Prateek Kiran Avatar answered Sep 28 '22 03:09

Prateek Kiran