How to create one hash from two arrays


(Radek Hnilica) #1

Hello,

How can I simply build one hash from two arrays. One containing keys
and second containing values.

keys = [‘a’, ‘b’, ‘c’]
vals = [1, 2, 3]

h = {‘a’=>1, ‘b’=>2, ‘c’=>3}

···


Radek Hnilica

No matter how far down the wrong road you’ve gone, turn back.
Turkish proverb


(Radek Hnilica) #2

How can I simply build one hash from two arrays. One containing keys
and second containing values.

keys = [‘a’, ‘b’, ‘c’]
vals = [1, 2, 3]

h = {‘a’=>1, ‘b’=>2, ‘c’=>3}

After sending question I found this solution

keys = res.fields
vals = res.result[0]

h = Hash.new(nil)	
0.upto(keys.length) do |i|
    h[keys[i]] = vals[i]
end

return h

but, could it be simpler?

···


Radek Hnilica

No matter how far down the wrong road you’ve gone, turn back.
Turkish proverb


(Dan Debertin) #3

Radek Hnilica writes:

How can I simply build one hash from two arrays. One containing keys
and second containing values.

Assuming a one-to-one correspondence between keys[0] and vals[0],
keys[1] and vals[1], etc:

keys.each_index { |k| h[keys[k]] = vals[k] }

Dan

···


airboss@nodewarrior.org
www.nodewarrior.org
ignorami: n:
The art of folding problem users into representational shapes.