Stefano Crocco
9/19/2007 6:25:00 PM
Alle mercoledì 19 settembre 2007, Une Bévue ha scritto:
> here is the goal:
>
> i've an Array of Unix pathes :
> forbidden = ["/Volumes/U3 System",
> "/Volumes/EMTEC KEY/emtec_dl",
> "/Volumes/EMTEC KEY/emtec_dl/Win98SE new driver.exe",
> "/Volumes/EMTEC KEY/emtec_dl/v233r001"
> ]
>
> i want to forbid access to those pathes BUT since, for example,
> "/Volumes/EMTEC KEY/emtec_dl/Win98SE new driver.exe" « belongs »
> to the path (it's below this path) "/Volumes/EMTEC KEY/emtec_dl"
> it is unusefull to have it in the Array.
>
> in the case above i'd like to return :
>
> forbidden = ["/Volumes/U3 System",
> "/Volumes/EMTEC KEY/emtec_dl"
> ]
>
> what i've done :
>
>
> class Array
> def includePath?(path)
> self.each { | x |
> return true if path.startsWith?(x)
> }
> return false
> end
> def getContainers!
> self.delete_if { | x | ( self - [ x ] ).includePath?( x ) }
> end
> end
>
> class String
> def startsWith?(dir)
> self.index(dir) === 0
> end
> end
>
> then forbidden.getContainers! gives me the expected result.
>
> what do you think about this solution ?
> could you propose a better one ?
>
> also, because english isn't my mother tongue, are my methods naming
> correct ?
This is my alternative solution:
def select_toplevel_paths arg
a = arg.dup.sort_by{|i| i.size}
a.inject([]) do |res, i|
res.any?{|j| i.index(j) == 0 } ? res : (res << i)
end
end
It doesn't change the contents of the array and it's not a method of class
Array, because, in my opinion, it's a too specialized method to be put in a
core class.
Regarding your code, I'd say names are correct, as far as English is
concerned. I'd like to give you a copule of suggestions:
* use underscores instead of camel-case (include_path? instead of includePath,
for example), because it's the more common style in the ruby community
* use start_with? instead of starts_with?. In the ruby standard library, there
are several cases in which both methods exist, with the ones ending in s being
obsolete (for example, File.exists? and File.exist?) For consistency, I think
it's better to follow the same convention.
Stefano