From: "David A. Black" Date: 2003-12-05T23:22:27+09:00 Subject: Batch key/value setting in a hash (was Re: Dumb question to which I ought to know the answer by now) Hi -- [Changed the subject to something more informative :-) ] On Fri, 5 Dec 2003, Austin Ziegler wrote: > On Fri, 5 Dec 2003 13:57:04 +0900, Mark J. Reed wrote: > > On Fri, Dec 05, 2003 at 01:45:36PM +0900, Austin Ziegler wrote: > >> hash = { :a => 3, :b => 2, :c => 1, :d => 0} > >> hash.update({ :a => 1, :b => 2, :c => 3 }) > > I know that, but in this case I have the keys and values in two arrays > > and want to match them up by position. In other words, I want to do this: > > > keys.each_with_index do > > |k, i| > > hash[k] = values[i] > > end > > > The equivalent of Perl @hash{@keys} = @values. > > Unfortunately, that won't work in Ruby because arrays can be keys, whereas > in Perl, hash keys can only be scalars. > > What you can do is: > > hash = nil; keys.zip(value) { |k, v| (hash ||= {})[k] = v } Or, using the handy flattenx extension from RAA: irb(main):001:0> require 'flattenx' => true irb(main):002:0> a = [ [1],2,3 ]; b = [ 4, [5,6], 7] => [4, [5, 6], 7] irb(main):003:0> Hash[*a.zip(b).flatten_by(1)] => {[1]=>4, 2=>[5, 6], 3=>7} (to avoid over-flattening) David -- David A. Black dblack@wobblini.net