在Ruby中,如何让我从一个数组的哈希? [英] In Ruby, how do I make a hash from an array?

查看:123
本文介绍了在Ruby中,如何让我从一个数组的哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数组:

arr = ["apples", "bananas", "coconuts", "watermelons"]

我也有一个函数˚F将在一个字符串输入执行操作,并返回一个值。此操作是非常昂贵的,所以我想memoize的哈希结果。

I also have a function f that will perform an operation on a single string input and return a value. This operation is very expensive, so I would like to memoize the results in the hash.

我知道我可以进行所需的哈希像这样的东西:

I know I can make the desired hash with something like this:

h = {}
arr.each { |a| h[a] = f(a) }

我想要做的是没有初始化小时,这样我可以只写是这样的:

What I'd like to do is not have to initialize h, so that I can just write something like this:

h = arr.(???) { |a| a => f(a) }

可以在做什么?

推荐答案

假设你有一个FUNTASTIC名称的功能:F

Say you have a function with a funtastic name: "f"

def f(fruit)
   fruit + "!"
end

arr = ["apples", "bananas", "coconuts", "watermelons"]
h = Hash[ *arr.collect { |v| [ v, f(v) ] }.flatten ]

会给你:

{"watermelons"=>"watermelons!", "bananas"=>"bananas!", "apples"=>"apples!", "coconuts"=>"coconuts!"}

更新:

正如评论中提到,红宝石1.8.7引入了一个更好的语法如下:

As mentioned in the comments, Ruby 1.8.7 introduces a nicer syntax for this:

h = Hash[arr.collect { |v| [v, f(v)] }]

这篇关于在Ruby中,如何让我从一个数组的哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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