DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

Convert to Hash from a couple of the key-value Array in Rails

πŸ€” 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}

πŸ”— Parent Note

Top comments (0)