假设,
string1 = "/var/usr/local/noob/"
我需要从最后一个字符开始到最接近它的“/”。
所以我期待:
remove_last_block_of_string()
我应该
“的/ var / USR /本地/小白”
如果我再次运行remove_last_block_of_string(),
"/var/usr/local"
再次运行,
"/var/usr"
答案 0 :(得分:4)
您可以使用:
sub(/\/[^\/]*$/, '')
,如,
>> "/var/usr/local/noob".sub(/\/[^\/]*$/, '')
=> "/var/usr/local"
>> _.sub(/\/[^\/]*$/, '')
=> "/var/usr"
但如果您正在操纵文件路径,最好使用Pathname库。
答案 1 :(得分:2)
或者,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"
我们可以获得更多乐趣:
>> 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"
或者,你可以monkeypatch String本身......
>> 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"
答案 2 :(得分:1)
如果您想处理一般情况,请使用其他答案提供的正则表达式。
然而,Ruby File
类处理您处理文件路径的特定情况:
File.dirname("/var/usr/local/noob/")
# outputs "/var/usr/local"
答案 3 :(得分:0)
下面: string1 =(string1.match /(.*)//)[1]如果string1.include? “/”
答案 4 :(得分:0)
您可以使用String和Array对象中的split和join方法:
>> 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"
现在,您只需将这两个函数放在一个对象中,该对象保存最后一个块被删除的字符串的状态。
我不太了解ruby,但可以实现以下内容:
// 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
}
}
或者用Ruby编写:P
BTW如果有人能够真正实现该课程,那将是很棒的,所以我可以学习它是如何完成的;)