π€ Situation
Assume that you have like this a pair of Array.
key=[:a,:b,:c]
value=[1,2,3]
π¦ Solution
Hash[*([key,value].transpose.flatten)]
{
:a => 1,
:b => 2,
:c => 3
}
π Mechanism
[key,value].transpose
#=> [[:a,1],[:b,2],[:c,3]]
# π
Warning: If the dimension isn't same, there will be an error
IndexError: element size differs.
[key,value].transpose.flatten
#=> [:a,1,:b,2,:c,3]
# The meaning of the * at the arg, the each element is passed as ISOLATE.
p *[key,value].transpose.flatten
#=>
# :a
# 1
# :b
# 2
# :c
# 3
# Then,
Hash[:a, 1, :b, 2, :c, 3]
=> {:a=>1, :b=>2, :c=>3}
Top comments (0)