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)