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?
The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
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.
The replace() method replaces a specified phrase with another specified phrase.
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"
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