Luigi Aversano Luigi Aversano - 4 months ago 7x
Ruby Question

Replacing a specific character in a string along with the immediate next character, Ruby only

Hi if I have a string of text like the following:

string = "%hello %world ho%w is i%t goin%g"

I want to return the following:

"Hello World hoW is iT goinG

So the % sign is a key that tells you the next character should be capitalized. The closest I have gotten so far is the following:

@thing = "%this is a %test this is %only a %test"

if @thing.include?('%')
indicator_position = @thing.index("%")
lowercase_letter_position = indicator_position + 1
lowercase_letter = @thing[lowercase_letter_position]


This returns the following:

"This is a Test this is %only a Test"

So it looks like I need to iterate through the string to make it work as it is only replacing the lowercase 't' but I can't get it to work. Any help would be great.


You can do this with gsub and a block:

string.gsub(/\%(.)/) do |m|

Using a block allows you to run arbitrary code on each match.