On Wed, 4 May 2005, Nick Woolley wrote: > Hi, > > Can anyone suggest an idiomatic ruby equivalent to this perl snippet? > > my %index = map { $_ => compute_something($_) } @files; > > Where @files is an array of filenames, and compute_something is a > subroutine which does some probably expensive operation on the file. > > The result is a hash indexing the file name to the computed result for > that file. This and it's grep equivalent is something I find quite > quite handy in perl. > > The best I came up with so far seems reletively clunky to me: > > index = Hash.new() > files.each {|f| index[f] = compute_something(f) } > > or: > > index = files.inject(Hash.new) {|i,f| i[f] = compute_something(f); i } > > I was wondering if there's a more succinct and readable way? > > TIA, > > Nick index = Hash::new{|h,f| h[f] = compute_something f} hashes can take a block to define how to initialize new values based on keys. one benefit is that this means the 'compute_something' bit is lazy. hth. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================