Jeff Schwab
8/13/2006 11:01:00 PM
Ken Bloom wrote:
> On Sat, 12 Aug 2006 17:43:02 +0000, Jeffrey Schwab wrote:
>
>> Trans wrote:
>>> Before I do and implement this myself, want to make sure it doesn;t
>>> already exist in some fashion: A command line utility like 'sh' but one
>>> that will ascend the directory tree to find the executable.
>> # Caution: On Windows, File.executable? is roughly equivalent to
>> File.exist?.
>>
>> def find_program_hierarchically(p)
>> d = File.expand_path('.')
>>
>> # Remove drive letter for Windows paths.
>> d.gsub!(/^[^\/]*/, '')
>>
>> while d.length != 0
>> f = "#{d}/#{p}"
>> return f if File.executable?(f)
>> d.gsub!(/\/[^\/]*$/, '')
>> end
>>
>> return nil
>> end
>>
>> puts find_program_hierarchically('main.rb')
>> puts find_program_hierarchically('nonesuch')
>> puts find_program_hierarchically('hello.txt')
>
> Yuck.
Thanks. :)
> Try this simpler code:
>
> require 'pathname'
>
> class Pathname
> def ancestors
> return [self] if self==parent
> return [self] + parent.ancestors
> end
> end
>
> def find_program_hierarchically(p)
> dir=Pathname.getwd.ancestors.find {|d| (d+p).executable?} + p
> end
I'm not convinced that's simpler. It's the same number of lines, brings
in an extra module, is recursive, and stuffs seven distinct identifiers
onto a single line. It does look nicer at first glance, though, since
it uses much less punctuation.