2013-11-25 149 views

回答

2

我發現rpartition作品相當不錯在這種情況下:

s = 'hello/world/of/stacks' 

p s.rpartition('/').first #=> "hello/world/of" 

或者,如果你想成爲幻想:

s, = s.rpartition('/') 

p s #= > "hello/world/of" 
+0

不錯(+1)。我認爲ruby類有一個方法可以用於任何人可以想象的單個函數。 ;) – lurker

1

使用rindex[]方法:

input.str[0, input.rindex(?/)] 
+1

只是不'字符串搞錯吧[a..b]'。這需要從範圍。我說的是需要長度的'string [a,b]'。 – quetzalcoatl

0
1.9.3p448 :024 > str = "hello/world/of/stacks" 
=> "hello/world/of/stacks" 

然後,您可以使用rindex找到字符串中的斜線的最後一個索引...

1.9.3p448 :025 > str.rindex("/") 
=> 14 

然後使用索引,你可以只抓取字符(不包括)斜線...

1.9.3p448 :026 > str[0..(14 - (str.length + 1))] 
=> "hello/world/of" 
1
File.dirname("hello/world/of/stacks") 
# => "hello/world/of" 
+0

如果它是一個你正在使用的路徑,這真的是一種方式! – hirolau