tags:

views:

238

answers:

5

assuming,

string1 = "/var/usr/local/noob/"

i need to start from the last character to the closest "/" preceiding it.

so i am expecting:

remove_last_block_of_string()

i should get

"/var/usr/local/noob"

if i run remove_last_block_of_string() again,

"/var/usr/local"

running it again,

"/var/usr"
+4  A: 

You can use this:

sub(/\/[^\/]*$/, '')

as in,

>> "/var/usr/local/noob".sub(/\/[^\/]*$/, '')
=> "/var/usr/local"
>> _.sub(/\/[^\/]*$/, '')
=> "/var/usr"

but if you're manipulating file paths, it would be better to use the Pathname library.

Peter
A: 

string1 = (string1.match /(.*)\//)[1] if string1.include? "/"

Jonas Elfström
+2  A: 

Or, string1 = string1[0...string1.rindex('/')]


>> def a s; s[0...s.rindex('/')]; end
>> t = "/var/usr/local/noob/"
=> "/var/usr/local/noob/"
>> t = a t
=> "/var/usr/local/noob"
>> t = a t
=> "/var/usr/local"

We could have even more fun:

>> class MyPath < String
>>   def root; self[0...self.rindex('/')]; end
>> end
=> nil
>> t = MyPath.new("/var/usr/local/noob/")
=> "/var/usr/local/noob/"
>> t = t.root
=> "/var/usr/local/noob"
>> t = t.root
=> "/var/usr/local"
>> t = t.root
=> "/var/usr"

Or, you could just monkeypatch String itself...

>> class String
>>   def root; self[0...self.rindex('/')]; end
>> end
=> nil
>> t = "/var/usr/local/noob/"
=> "/var/usr/local/noob/"
>> t = t.root
=> "/var/usr/local/noob"
>> t = t.root
=> "/var/usr/local"
DigitalRoss
A: 

You could use split and join methods from String and Array objects:

>> s = "/var/usr/local/noob/"
=> "/var/usr/local/noob/"
>> p = s.split('/')
=> ["", "var", "usr", "local", "noob"]
>> p.slice!(-1)
=> "noob"
>> p.join('/')
=> "/var/usr/local"
>> p.slice!(-1)
=> "local"
>> p.join('/')
=> "/var/usr"
>> p.slice!(-1)
=> "usr"
>> p.join('/')
=> "/var"

Now you just have to put these two functions in an object that holds the state of the string whose last block is being removed.

I don't know much of ruby but something like the following could be implemented:

 // Pseusdo - Java
 class LastBlockRemoved {
      private String string;
      private Array currentState;

      public String remove_last_block_of_string() {
          currentState = string.split("/");
          string = currentState.join("/");
          return string
      }

 }

Or however that is coded in Ruby :P

BTW It would be great if someone could actually implement that class, so I can learn how it is done ;)

OscarRyz
+1  A: 

If you want to handle the general case, then use a regex as provided by other answers.

However the Ruby File class handles the specific case where you are dealing with file paths:

File.dirname("/var/usr/local/noob/")
# outputs "/var/usr/local"
madlep