Tiggerius wrote:
keys = ["1", "2", "3", "4", "5"]
vals = ["a", "b", "c", "d", "e", "f", "g"]
I want h = {"1"=>"a", "2"=>"b", "3"=>"c", "4"=>"d", "5"=>"e"}
right now I do it by:
for i in 0..keys.size-1
h[keys[i]]=vals[i]
end
is there a ruby way, more slick way of doing this? Thanks.
Array#zip is a good way to get started. It takes two Arrays and
'zips' them together: [1].zip([2]) => [[1, 2]]. #inject can be
used to accumulate data, here we accumulate into the Hash (which
is the initial {} there):
keys.zip(values).inject({}) {|hash, (k, v)| hash[k] = v; hash}
An alternative syntax would leverage the ability of Hash. to
take an even number of parameters and construct its keys and
values from that: Hash[1, 2] => {1 => 2}. To create separate
parameters from the contents of an Array, use the splat-operator
(*): *[1, 2] => 1, 2:
Hash[*keys.zip(values).flatten]
This only works when you do not have nested Arrays, though.
E