CrispyDuck
CrispyDuck

Reputation: 431

Remove everything from trailing forward slash

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

Answers (5)

anothermh
anothermh

Reputation: 10526

file.split('/').take(file.split('/').size - 1).join('/') + ']'
=> "[/my/directory]"
  1. Split the string into an array of strings separated by /
  2. Take all the array elements except the last element
  3. Join the strings together, re-inserting / between them
  4. Add a trailing ]

Upvotes: 0

Cary Swoveland
Cary Swoveland

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

tadman
tadman

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

Rohit Namjoshi
Rohit Namjoshi

Reputation: 679

file = "[/my/directory/file-*.log]"
file.sub(/^(.+)\/([^\/]+)\]/, '\1/]')
=> "[/my/directory/]"

Upvotes: -1

tlehman
tlehman

Reputation: 5167

You can use File.dirname:

File.dirname("/my/directory/file-*.log")
=> "/my/directory"

Upvotes: 4

Related Questions