Reputation: 9201
How do I replace only part of the String in a Ruby code?
Supposed I have a text file that contains multiple occurrences of the keyword "JVM_MEM_ARGS_64BIT"
JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"
and I only want to replace the first occurrence, I can use the #sub instead of gsub
a.sub('JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"', 'JVM_MEM_ARGS_64BIT="-Xms512m -Xmx1024m"')
however not all files contains
JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"
some could be
JVM_MEM_ARGS_64BIT="-Xms256m -Xmx512m"
I am not sure how to do this in a ruby code? I can search for the keyword "JVM_MEM_ARGS_64BIT" only but how do I delete the existing value assignment and replace it with JVM_MEM_ARGS_64BIT="-Xms512m -Xmx1024m
Newbie Ruby developer.
Upvotes: 0
Views: 78
Reputation: 121010
String#sub
accepts a regular expression as a first param:
replacement = 'JVM_MEM_ARGS_64BIT="-Xms512m -Xmx1024m"'
a.sub(/JVM_MEM_ARGS_64BIT="-Xms\d+m -Xmx\d+m"/, replacement)
Upvotes: 1