Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

regex

ruby

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

The % 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]

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

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.

like image 757
Luigi Aversano Avatar asked Feb 07 '23 22:02

Luigi Aversano


1 Answers

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.

like image 104
tadman Avatar answered Feb 09 '23 11:02

tadman