Ruby Ruby 数组转 hash

riskgod · March 12, 2015 · Last by liuhui1226 replied at January 20, 2019 · 4297 hits

数组 转 hash

有 什么办法 to_h 不算~

解决 zip

h = Hash[*a.flatten]

根据需求自己写个方法吧,比如: [1,2].to_h => {1 => 2} [1,2].to_h => {1 => 1, 2 => 2},这个都得看需求

h = Hash[*a.flatten] 这种方式如果遇到

[ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]

就会报错,还是用下面这种方法吧:

Hash[a3.map {|key, value| [key, value]}]

https://codeday.me/bug/20170605/23146.html

You need to Sign in before reply, if you don't have an account, please Sign up first.