From: Joel VanderWerf Date: 2005-05-04T07:22:37+09:00 Subject: Re: mapping an array to a hash? 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? I'm not aware of anything more succinct to do what you wrote here, but if you want to defer the expensive operation, you can do this: index = Hash.new { |h,f| h[f] = compute_something(f) } Maybe there should be something like this: class Array def hashmap h={} each {|x| h[x] = yield x} h end end [1,2,3].hashmap {|x| x*10} # => {1=>10, 2=>20, 3=>30}