From: Robert Klemme Date: 2005-05-04T14:29:32+09:00 Subject: Re: mapping an array to a hash? "John Carter" schrieb im Newsbeitrag news:Pine.LNX.4.61.0505041025210.25628@parore.tait.co.nz... > On Wed, 4 May 2005, Nick Woolley wrote: > >> Can anyone suggest an idiomatic ruby equivalent to this perl snippet? >> >> my %index = map { $_ => compute_something($_) } @files; > >> The best I came up with so far seems reletively clunky to me: >> >> index = Hash.new() >> files.each {|f| index[f] = compute_something(f) } > > If you want mind bending and obscure, try... > > index = Hash.new{|hash,key| hash[key] = compute_something(key)} > > and then somewhere totally elsewhen in the code... > > files.each{|f| index[f]} That's not really equivalent to what Nick requested and it's more clunky also. I prefer a solution with - guess what - #inject, but Hash[] does work, too: >> a = [1,2,3] => [1, 2, 3] >> a.inject({}) {|h,i| h[i]=i+10; h} => {1=>11, 2=>12, 3=>13} >> Hash[ *a.map{|i| [i,i+10]}.flatten ] => {1=>11, 2=>12, 3=>13} Kind regards robert