Ruby Ruby 数组转 hash

riskgod · 2015年03月12日 · 最后由 liuhui1226 回复于 2019年01月20日 · 4299 次阅读

数组 转 hash

有 什么办法 to_h 不算~

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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号