Robert Klemme
11/21/2007 6:36:00 PM
On 21.11.2007 16:00, Casimir wrote:
> ...index in a hash...
> ...all directories under 'src'...
> ...that contain filetypes in 'ft[]'...
> ...without getting lost in arrays inside arrays..
>
> #Here is my try
> src="/"
> tmpindex = []
> filetypes = [".jpg", ".png", ".gif", ".bmp"]
> filetypes.each { |typ| tmpindex << Dir[src+"**/*"+typ] }
>
> index={}
> tmpindex.each { |fpath|
> dirpath = File.dirname(File.expand_path(fpath.to_s))
> index[dirpath] = File.basename(fpath.to_s)
> }
> puts index
> #bleed
> #end
Are you sure you want to remember only one file per directory? If not:
EXTENSIONS = %w{jpg png gif bmp}
index = Hash.new {|h,k| h[k]=[]}
Dir["**/*.{#{EXTENSIONS.join(',')}}"].each do |f|
dir, base = File.split f
index[dir] << base
end
And, for the record, the solution with #inject:
EXTENSIONS = %w{jpg png gif bmp}
index = Dir["**/*.{#{EXTENSIONS.join(',')}}"].inject(
Hash.new {|h,k| h[k]=[]}) do |h,f|
dir, base = File.split f
h[dir] << base
h
end
Cheers
robert