Page 1 of 1
Find & Replace in Ruby
Posted: Wed Sep 28, 2016 10:56 pm
by Wassaka
Hi!! First, I don't know anything about Ruby.. But i am trying to do "Find/Search and Replace" but searching into a word. For example: "Hello word", "e" will be replaced by "3". So, "H3llo word". Is this possible?? Thanks!! And sorry about my bad english

Re: Find & Replace in Ruby
Posted: Thu Sep 29, 2016 12:05 pm
by tulamide
The string class has the methods :sub and :gsub, which replace ("substitute") based on following logic:
Code: Select all
mystring = "Hello World".sub("e", "3") # results in "H3llo world"
mystring = "Hello there".sub("e", "3") # results in "H3llo there"
Code: Select all
mystring = "Hello there".gsub("e", "3") # results in "H3llo th3r3"
For more complex substitutions you need to use a regexp pattern.
Re: Find & Replace in Ruby
Posted: Thu Sep 29, 2016 1:11 pm
by Wassaka
tulamide wrote:The string class has the methods :sub and :gsub, which replace ("substitute") based on following logic:
Code: Select all
mystring = "Hello World".sub("e", "3") # results in "H3llo world"
mystring = "Hello there".sub("e", "3") # results in "H3llo there"
Code: Select all
mystring = "Hello there".gsub("e", "3") # results in "H3llo th3r3"
For more complex substitutions you need to use a regexp pattern.
Thanks you very much!!!
