将数组转换为哈希,其中键是索引 [英] Convert an array to hash, where keys are the indices

查看:33
本文介绍了将数组转换为哈希,其中键是索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数组转换为哈希,其中键是索引,值是该索引处的元素.

I am transforming an array into a hash, where the keys are the indices and values are the elements at that index.

这是我的做法

# initial stuff
arr = ["one", "two", "three", "four", "five"]
x = {}

# iterate and build hash as needed
arr.each_with_index {|v, i| x[i] = v}

# result
>>> {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

有没有更好的(在任何意义上的更好"这个词)的方法来做到这一点?

Is there a better (in any sense of the word "better") way to do it?

推荐答案

arr = ["one", "two", "three", "four", "five"]

x = Hash[(0...arr.size).zip arr]
# => {0=>"one", 1=>"two", 2=>"three", 3=>"four", 4=>"five"}

这篇关于将数组转换为哈希,其中键是索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆