ruby - 将数组转换为 ruby​​ 中的嵌套哈希

标签 ruby arrays hash

<分区>

我有以下数组

['a', 'b', 'c']

如何将其转换为如下所示的散列:

{'a' => { position: index of array element a }, 'b' ...., 'c' ... }

最好的问候 格奥尔基。

最佳答案

首先,您可以使用 Array#mapEnumerator#with_index 方法创建如下所示的数组:

ary = ['a', 'b', 'c']
temporary = ary.map.with_index { |e, i| [e, { position: i }] }
# => [["a", {:position=>0}], ["b", {:position=>1}], ["c", {:position=>2}]]

然后您可以使用 Array#to_h 将结果数组转换为散列自 Ruby 2.1 起可用的方法:

temporary.to_h
# => {"a"=>{:position=>0}, "b"=>{:position=>1}, "c"=>{:position=>2}}

对于旧版本的 Ruby,Hash.[]方法将执行:

Hash[temporary]
# => {"a"=>{:position=>0}, "b"=>{:position=>1}, "c"=>{:position=>2}}

关于ruby - 将数组转换为 ruby​​ 中的嵌套哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21937328/

相关文章:

ruby-on-rails - 从散列/YAML 中删除所有空元素?

python - 如何应用哈希算法而不是 for 循环来降低 python 中的时间复杂度?

c++ - Rabin-Karp 算法代码中的负哈希值

ruby - Cron 不会执行 ruby​​ 脚本

ruby - 如何在网页上使用 Mechanize 到 'Show More' 单击(显然)无格式按钮/链接

c - 如何定义一个全局数组(获取另一个函数的长度)?

javascript - jQuery:仅打印数组中的一个结果

ruby-on-rails - Rails Partial (Rails 3, HAML) 任意慢

ruby - 查找 Ruby 在运行程序时打开的所有当前文件

java 检查一个数字的平方中的数字是否不在其立方中