ruby-on-rails – 将Ruby哈希转换为数组

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 将Ruby哈希转换为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个形式的哈希
{:a => {“aa”=> 11,“ab”=> 12},:b => {“ba”=> 21,“bb”=> 22}}

如何将其转换为{:a =>形式[[ “AA”,11],[ “AB”,12]],:B => [ “BA”,21],[ “BB”,22]]}

解决方法

如果要修改原始哈希,可以执行以下操作:
hash.each_pair { |key,value| hash[key] = value.to_a }

来自Hash#to_a的文档

Converts hsh to a nested array of [
key,value ] arrays.

h = { "c" => 300,"a" => 100,"d" => 400,"c" => 300 }

h.to_a #=> [["c",300],["a",100],["d",400]]

原文链接:https://www.f2er.com/ruby/270915.html

猜你在找的Ruby相关文章