转换的Ruby数组哈希 [英] Converting Ruby array into a hash

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

问题描述

我试图写一个名为方法 my_transform ,它接受一个数组如下:

I am attempting to write a method named my_transform that takes an array as follows:

items = ["Aqua", "Blue", "Green", "Red", "Yellow"]

和显示的项目指标如下:

and displays the items' indexes as follows:

item_to_position = {"Aqua"=>0, "Blue"=>1, "Green"=>2, "Red"=>3, "Yellow"=>4}

我应该能够执行:

I should be able to execute:

my_transform(items) == item_to_position

和接收真正

我已经使用考虑的。我首先要说的是:

I have contemplated using each_with_index. Should I begin by saying:

items = ["Aqua", "Blue", "Green", "Red", "Yellow"]

hash = Hash[*array]

def my_transform

我要的字符串转换为哈希值。任何帮助是AP preciated。

I have to convert the string to a hash. Any help is appreciated.

推荐答案

我会用的 阵列#to_h

items = ["Aqua", "Blue", "Green", "Red", "Yellow"]
items.each_with_index.to_h
#=> { "Aqua"=>0, "Blue"=>1, "Green"=>2, "Red"=>3, "Yellow"=>4 }

注意 to_h 在红宝石2.1引入了

使用 to_h 你的 my_transform 方法可能看起来是这样的:

Using to_h your my_transform method could look like this:

def my_transform(items)
  items.each_with_index.to_h
end

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

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