Luigi Aversano Luigi Aversano - 6 months ago 9
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]

@thing.gsub!("%#{lowercase_letter}","#{lowercase_letter.upcase}")
end


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.

Answer

You can do this with gsub and a block:

string.gsub(/\%(.)/) do |m|
  m[1].upcase
end

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

Comments