Find & Replace in Ruby

For general discussion related FlowStone
Post Reply
Wassaka
Posts: 85
Joined: Wed Dec 30, 2015 3:41 am

Find & Replace in Ruby

Post 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 :(
tulamide
Posts: 2714
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

Re: Find & Replace in Ruby

Post 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.
"There lies the dog buried" (German saying translated literally)
Wassaka
Posts: 85
Joined: Wed Dec 30, 2015 3:41 am

Re: Find & Replace in Ruby

Post 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!!! :D
Post Reply