Reputation: 431
Starting with this string:
file = "[/my/directory/file-*.log]"
I want to remove anything that comes after the trailing /
and the closing square bracket, so the returned string is:
file = "[/my/directory/]"
I wondered if someone could recommend the safest way to do this.
I have been experimenting with chomp
but I’m not getting anywhere, and gsub
or sub
doesn’t seem to fit either.
Upvotes: 1
Views: 97
Reputation: 10526
file.split('/').take(file.split('/').size - 1).join('/') + ']'
=> "[/my/directory]"
/
/
between them]
Upvotes: 0
Reputation: 110675
Here are three non-regex solutions:
file[0..file.rindex('/')] << ']'
file.sub(file[file.rindex('/')+1..-2], '')
"[#{File.dirname(file[1..-2])}]"
All return "[/my/directory/]"
.
Upvotes: 1
Reputation: 211560
If it's stuck inside the brackets, you can always write a custom replacement function that calls out to File.dirname
:
def squaredir(file)
file.sub(/\[([^]]+)\]/) do |m|
'[%s]' % File.dirname($1)
end
end
Then you get this:
squaredir("[/my/directory/file-*.log]")
# => "[/my/directory]"
Upvotes: 1
Reputation: 679
file = "[/my/directory/file-*.log]"
file.sub(/^(.+)\/([^\/]+)\]/, '\1/]')
=> "[/my/directory/]"
Upvotes: -1
Reputation: 5167
You can use File.dirname
:
File.dirname("/my/directory/file-*.log")
=> "/my/directory"
Upvotes: 4