Reputation: 214
I have a string “shared/errors”, and I’d like for the the word “error” to be prepended with an underscore, so as to achieve “shared/_errors” Is there some ruby magic for doing this?
Upvotes: 1
Views: 73
Reputation: 11323
Perhaps all answers are valid here, but I did see that OP references 'errors' by name. Rather than the slash.
string.gsub!('error', '_error')
should change the original string, and do so, for all occurrences that may happen in the string. Of course, I have a feeling the slash is important, so perhaps the more correct string.gsub!('/error', '/_error')
will do better.
Upvotes: 1
Reputation: 126742
Assuming there is only a single slash in the string, all that is necessary is
string.sub!(%r|(?<=/)|, '_')
or, if you prefer,
string.sub!('/', '/_')
If there are multiple slashes in the string and you only want to affect the last one, then you want
string.sub!(%r|(?=[^/]*\z)|, '_')
Upvotes: 2
Reputation: 14048
If you only want to do this on the last occurrence of the forward slash you can insert an underscore at the index of the slash:
string.insert(string.rindex('/') + 1, '_')
Upvotes: 1
Reputation: 3408
Why not
path = 'shared/errors' # or whatever it is
dir, file = path.match(/^(.*\/)([^/]*)$/).captures
path = dir + "_" + file
This will get the two parts of the string:
shared/errors ==> shared/ + errors
And then patch them back together to form the desired string.
Upvotes: 0