Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would one use the replace method of a string?

Tags:

ruby

I was messing around and decided to see if "abcde".replace("a", "e") would return "ebcde". Turns out this isn't how replace works (I admit I guessed at the method name seeing if one such existed for these purposes).

Instead after reading the docs I found that it has odd behavior.

string = "abcde"
string.replace("e") #=> "e"

string is now "e".

What is the point of the replace method? To me it looks like a setter method, but you could just as easily do string = "e".

Are there specific use-cases for replace?

like image 544
David Avatar asked May 25 '14 07:05

David


People also ask

What is the use of replace method?

The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

Why find and replace method is used in string?

The Java string replace() method is used to replace all instances of a particular character or set of characters in a string with a replacement string.

Which method can be used to replace parts of a string?

The replace() method replaces a specified phrase with another specified phrase.


1 Answers

replace changes the contents of the current instance, rather than assigning a new instance. See differences:

a = 'old_string'
b = a
b.replace 'new_string'
a
# => "new_string"

vs

a = 'old_string'
b = a
b = 'new_string'
a
# => "old_string"
like image 53
Uri Agassi Avatar answered Oct 21 '22 18:10

Uri Agassi