Luigi Aversano Luigi Aversano - 1 year ago 54
Ruby Question

How to replace a specific character in a string along with the immediate next character

I have a string of text:

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

I want to return the following:

"Hello World hoW is iT goinG

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

@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:

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download