Reputation:
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"
Upvotes: 0
Views: 1353
Reputation: 31428
Here: string1 = (string1.match /(.*)//)[1] if string1.include? "/"
Upvotes: 0
Reputation: 49676
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"
Upvotes: 1
Reputation: 146073
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"
Upvotes: 2
Reputation: 199225
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 ;)
Upvotes: 0