From: Ken Bloom Date: 2006-08-14T14:05:07+09:00 Subject: Re: [OT] sh command that ascends dir tree for executable On Sun, 13 Aug 2006 23:01:19 +0000, Jeffrey Schwab wrote: > 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. I have a habit of writing really really long one-liners. --Ken -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/