Home > Software design >  Replace the second integer/number in a string
Replace the second integer/number in a string

Time:06-03

Given different Strings with each two Integers, what is the easiest way in Ruby (2.7) to replace the second Integer?

Example:

'We are there from 2 to 5 oclock'
'You can stack 15 onto 22 boxes'

So far I am using string::gsup but I am wondering if there is a better way?

CodePudding user response:

gsub is the easiest way to achieve this job.

Input

a='We are there from 2 to 5 oclock'

Code

p a.gsub(/\D*\d \D \K\d /,"10000")

Output

"We are there from 2 to 10000 oclock"
  •  Tags:  
  • ruby
  • Related