From: "David A. Black" Date: 2008-07-28T20:35:02+09:00 Subject: Re: head/tail split for path Hi -- On Mon, 28 Jul 2008, ara.t.howard wrote: > > On Jul 26, 2008, at 1:54 PM, Trans wrote: > >> I need to split a path by head/*tail. >> >> Ex. >> >> File.head_tail_split('home/foo/bar') #=> [ 'home', 'foo/bar' ] >> >> Sure, I can write a clumsy loop like the following: >> >> def File.head_tail_split(fname) >> s = fname >> t = [] >> h = nil >> until s == '.' >> t << h >> s, h = *split(s) >> end >> return h, File.join(*t.compact) >> end >> >> But I'm betting there's a better way. Or maybe there's already an easy >> way I'm overlooking > > > > cfp:~ > cat a.rb > path = File.join 'a', 'b', 'c' > > head, tail = path.split( File::SEPARATOR, 2 ) > > p :head => head, :tail => tail > > > > cfp:~ > ruby a.rb > {:tail=>"b/c", :head=>"a"} Ironically, I tried that first and discarded it because I had misunderstood Tom's question and thought he wanted dirname/basename, and then didn't resurrect it when I finally understood :-) The only tweak I might make would be to use Pathname#clean (or roll one's own) in case there are consecutive separators. David -- Rails training from David A. Black and Ruby Power and Light: * Advancing With Rails August 18-21 Edison, NJ * Co-taught by D.A. Black and Erik Kastner See http://www.rubypal.com for details and updates!