I need to change the value of a parameter (OFFSET=) by adding 20 to its value. So instead of having OFFSET=0 I get OFFSET=20. Now, I can't be sure that the value for OFFSET is equal to 0, so I need to extract it. Here is what I have tried:
aNumber = "myValue=20".match(/myValue=(\d+)/)[1].to_i
bString = "OFFSET=#{aNumber}"
newValue = bString.gsub(/OFFSET=#{aNumber}/, "OFFSET=#{aNumber + 20}")
Now, to use #{}
I obviously need a string with ""
, which I can't use together with .gsub()
or .match()
. Right now I am not able to gsub because it can't get the value of aNumber
. How can that be done?
You can use gsub with a block:
x = "myValue=20"
p x.gsub(/\d+/){|x| x.to_i + 20} # => myValue=20
or if you have a longer string and only want to change myValue:
x = "firstValue=10, myValue=20, otherValue=30"
p x.gsub(/(?<=myValue=)(\d+)/){|x| x.to_i + 20} # => firstValue=10, myValue=40, otherValue=30
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.